這是我在這個社區的第一個問題,我想得到我的問題的答案,假設我有兩個串列 A 和 B:
List<int> listA = new List<int>();
List<int> listB = new List<int>();
listA.Add(1);
listA.Add(2);
listA.Add(8);
listB.Add(1);
listB.Add(1);
listB.Add(1);
listB.Add(2);
listB.Add(2);
listB.Add(2);
listB.Add(2);
我想計算 listB 中已經存在于 listA 中的每個元素的出現次數,如果不存在則添加零:
這是我嘗試過的:
var result = listB.GroupBy(x => x).ToDictionary(k => k.Key, v => v.Count());
foreach(var res in result.Values)
Console.WriteLine(res); // it will print only {3,4}
預期結果將是:
// { 3,4,0} => 3 is the occurrences number of 1 , 4 is the occurrences number of 2 ,and 0 is the number occurrences of 8
我怎樣才能達到這個結果?
uj5u.com熱心網友回復:
我會使用 linq .Count() 擴展,它將計算滿足條件的專案數。是的,這將迭代串列比必要的次數更多,但它不會創建任何不必要的物件,而且它非常易讀:
var countOccurences = new List<int>();
foreach (var inA in listA)
{
countOccurences.Add(listB.Count(inB => inB == inA));
}
Console.WriteLine(string.Join(", ", countOccurences));
一旦你讓回圈作業,那么應該很容易看出它可以在一個陳述句中完成:
var countOccurences = listA.Select(inA => listB.Count(inB => inA == inB));
uj5u.com熱心網友回復:
修復你的代碼
var result = listB.GroupBy(x => x).ToDictionary(k => k.Key, v => v.Count());
foreach(var ent in listA)
Console.WriteLine(result.ContainsKey(ent)?result[ent]:0);
uj5u.com熱心網友回復:
一行 Linq 陳述句
listA.Select(a => listB.Contains(a) ? a : 0 ).Select(r=>listB.Count(w=> w==r)).ToList();
uj5u.com熱心網友回復:
在 LINQ 中使用左外連接是一個很好的問題。這是一篇關于它的文章。這是性能最佳的解決方案,因為您只需對集合進行一次迭代,這對于大型集合或常用方法很重要。
這是您的問題的示例:
var result = from a in listA
join b in listB.GroupBy(x => x) on a equals b.Key into gj
from subList in gj.DefaultIfEmpty()
select new
{
Number = a,
Count = subList?.Count() ?? 0
};
您也可以使用 GroupJoin 和方法鏈接,但我認為它更難閱讀:
var result = listA
.GroupJoin(listB.GroupBy(x => x), a => a, b => b.Key, (a, gj) => new { a, gj })
.SelectMany(@t => @t.gj.DefaultIfEmpty(), (@t, subList) => new { Number = @t.a, Count = subList?.Count() ?? 0 });
之后,結果將包含一組帶有欄位Number和Count3 個元素的匿名型別:{1, 3}, {2, 4}, {8, 0}.
從評論更新(感謝 Caius Jard):如果你不能使用空條件運算子,你可以用顯式檢查替換它:subList == null ? 0 : subList.Count()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/454025.html
