LINQ解及其解释。还有关于调试的LINQPad提示。
List<List<uint>> AllLists = new List<List<uint>>();
List<uint> TestList1 = new List<uint>();
List<uint> TestList2 = new List<uint>();
List<uint> TestList3 = new List<uint>();
TestList1.Add(0x18A);
TestList1.Add(0x188);
TestList1.Add(0x188);
TestList1.Add(0x188);
TestList1.Add(0x188);
TestList1.Add(0x188);
TestList1.Add(0x188);
TestList1.Add(0x670);
TestList2.Add(0x670);
TestList2.Add(0x670);
TestList3.Add(0xBADC0DE); //this one is empty.. but could contain some useless ones (not 0x670).
AllLists.Add(TestList1.ToList());
AllLists.Add(TestList2.ToList());
AllLists.Add(TestList3.ToList());
var numbers = AllLists
.Select(x => x
.GroupBy(y => y) // group the numbers in each sub-list
.Select(z => new { Key = z.Key })) // select only the key in each sub-list
.SelectMany(x => x) // flatten the lists
.GroupBy(x => x.Key) // group by the keys
.OrderByDescending(x => x.Count()) // sort the count of keys from largest to smallest
;
var mostCount = numbers
.Select(x => x.Count()) // select the count of keys only
.Take(1) // take one, actually this line is not needed. you can remove it
.FirstOrDefault(); // take the largest count of key (the counts were sorted in previous linq statement)
var numberWithMostCount = numbers
.Where(x => x.Count() == mostCount) // filter the largest count of in the lists
.Select(x => x.Key) // select the key only
;
foreach (var n in numberWithMostCount)
Console.WriteLine(n); // print all key who has the largest count
您可能会注意到,在前面的编辑中,我在LINQ语句中调用了一些Dump()方法。我在LinqPad中编写并调试了代码。它有Dump()方法,可以很容易地看到LINQ操作的结果。假设我在代码中放了一个Dump()方法(如果图片太小,请在新选项卡中打开图片)。Dump()方法显示LINQ方法的执行结果。可以在每个Linq方法之后放置一个Dump()方法。尝试在任何带有注释的行中添加Dump()方法,最好一次添加一个或两个Dump()。
Lasse Vågsæther Karlsen
. 使用Distinct()删除重复项。谢谢,拉丝·维格瑟·卡尔森。
var numbers = AllLists
.Select(x => x.Distinct()) // remove duplicates
.SelectMany(x => x) // flatten the lists
.GroupBy(x => x) // group by the keys
.OrderByDescending(x => x.Count()) // sort the count of keys from largest to smallest
;