4 回答

TA貢獻1895條經驗 獲得超3個贊
有很多方法可以解決這個問題;我的建議是將它分解成許多較小的問題,然后編寫一個簡單的方法來解決每個問題。
這是一個更簡單的問題:給定一個序列T,給我返回一個刪除了“雙倍”項目的序列T:
public static IEnumerable<T> RemoveDoubles<T>(
this IEnumerable<T> items)
{
T previous = default(T);
bool first = true;
foreach(T item in items)
{
if (first || !item.Equals(previous)) yield return item;
previous = item;
first = false;
}
}
偉大的。這有什么幫助?因為現在解決您的問題是:
int count = myList.Select(x => x > 2).RemoveDoubles().Count(x => x);
跟著。
如果您有myListas{0, 0, 3, 3, 4, 0, 4, 4, 4}那么結果Select是{false, false, true, true, true, false, true, true, true}.
的結果RemoveDoubles是{false, true, false, true}。
的結果Count是 2,這是期望的結果。
盡可能使用現成的部件。如果你不能,試著解決一個簡單的、一般的問題,讓你得到你需要的東西;現在您有了一個工具,您可以將其用于需要您刪除序列中重復項的其他任務。

TA貢獻1843條經驗 獲得超7個贊
該解決方案應該可以達到預期的效果。
List<int> lsNums = new List<int>() {0, 0, 3, 3, 4, 0, 4, 4, 4} ;
public void MainFoo(){
int iChange = GetCritcalChangeNum(lsNums, 2);
Console.WriteLine("Critical change = %d", iChange);
}
public int GetCritcalChangeNum(List<int> lisNum, int iCriticalThreshold) {
int iCriticalChange = 0;
int iPrev = 0;
lisNum.ForEach( (int ele) => {
if(iPrev <= iCriticalThreshold && ele > iCriticalThreshold){
iCriticalChange++;
}
iPrev = ele;
});
return iCriticalChange;
}

TA貢獻1828條經驗 獲得超6個贊
您可以創建一個擴展方法,如下所示。
public static class ListExtensions
{
public static int InstanceCount(this List<double> list, Predicate<double> predicate)
{
int instanceCount = 0;
bool instanceOccurring = false;
foreach (var item in list)
{
if (predicate(item))
{
if (!instanceOccurring)
{
instanceCount++;
instanceOccurring = true;
}
}
else
{
instanceOccurring = false;
}
}
return instanceCount;
}
}
并像這樣使用您新創建的方法
current.InstanceCount(p => p > 2)

TA貢獻1942條經驗 獲得超3個贊
執行此操作的另一種方法System.Linq是遍歷列表,同時選擇itemitself 和 it's index,然后返回true每一項大于value且前一項小于或等于 的項value,然后選擇結果數true。當然索引有一個特例0,我們不檢查前一項:
public static int GetSpikeCount(List<int> items, int threshold)
{
return items?
.Select((item, index) =>
index == 0
? item > threshold
: item > threshold && items[index - 1] <= threshold)
.Count(x => x == true) // '== true' is here for readability, but it's not necessary
?? 0; // return '0' if 'items' is null
}
示例用法:
private static void Main()
{
var myList = new List<int> {0, 0, 3, 3, 4, 0, 4, 4, 4};
var count = GetSpikeCount(myList, 2);
// count == 2
}
- 4 回答
- 0 關注
- 197 瀏覽
添加回答
舉報