5 回答

TA貢獻1993條經(jīng)驗 獲得超6個贊
現(xiàn)在我需要循環(huán)遍歷整個列表,搜索有 10 個條目的 Number 并將它們存儲在新列表中。
Foeach 不太適合做這項工作。您需要 2 個 For 循環(huán)。一個用于每個(不同的)項目編號,一個用于比較。由于您的集合是有序的,因此您可以使用它來避免對基本集合進行多次迭代。每次新系列開始時,您都可以記住內(nèi)循環(huán)的索引結束并在外循環(huán)中跳轉到記住的位置:
for (int i = 0; i < NumberList.Count; i++)
{
tempList.Clear();
for (int j = i+1; j < NumberList.Count; j++)
{
if (NumberList[i].Number == NumberList[j].Number)
{
tempList.Add(NumberList[i]);
}
else
{
// Note that a new series of numbers has began and jump to this position
i = j;
break; // end this counting procedure
}
}
// at this point evalueate the counter
if (tempList.Count >= 10)
{
finalList.AddRange(tempList.Take(10));
}
}
簡短的 Linq 解決方案可能如下所示:
NumberList.GroupBy(x => x.Number).Where(x => x.Count() >= 10).SelectMany(x => x.Take(10));
只需將具有相同值的所有數(shù)字收集到分組集合中即可。
然后對其應用過濾器,檢查哪一個符合您出現(xiàn) 10 次或以上的標準。
然后僅選擇這些項目/取消它們的分組并僅選取前 10 個;

TA貢獻1780條經(jīng)驗 獲得超5個贊
您可以使用 Linq 來執(zhí)行此操作。例如,
var finalList = numberList .GroupBy(a => a.Number) .Where(a => a.Count() >= 10) .SelectMany(a => a.OrderBy(b => b.CloseTime).Take(10)) .ToList();
所以首先我們使用 來按數(shù)字分組GroupBy
。然后,我們使用 限制僅包含 10 個或更多條目的分組Where(a => a.Count() >= 10)
。然后我們使用SelectMany
來展平分組,并使用 來選擇每個分組的前 10 個元素Take
,并使用OrderBy
來確保它們的順序一致。

TA貢獻1835條經(jīng)驗 獲得超7個贊
NumberList .GroupBy(x => x.Number) .Where(groupings => grouping.Count() > 10) .SelectMany(groupings => groupings) .ToList()

TA貢獻1998條經(jīng)驗 獲得超6個贊
var tempList = new List<NumberList>(); // temporary list var finalList = tempList.GroupBy(t => t.Number) .Where(t => t.Count() >= 10) .SelectMany(t => t.Take(10)) //take 10 elements from filtered data .ToList();

TA貢獻1811條經(jīng)驗 獲得超5個贊
您可以在 Number 字段上創(chuàng)建一個不同的值,并使用不同的結果循環(huán)該對象
foreach (var item in numList.Select(x=> x.Number).Distinct())
{
int counter = 0;
if(numList.Where(x=> x.Number.Equals(item)).Count() >= 10 )
{
foreach( var item2 in numList.Where(x=> x.Number.Equals(item)) ){
if(counter <10 ) {
finalList.Add(item2);
counter ++;
}
}
}
}
foreach(var test in finalList)
Console.WriteLine(string.Format("{0}, {1}", test.Number, test.Profit));
- 5 回答
- 0 關注
- 278 瀏覽
添加回答
舉報