[英]Finding and counting common list elements across multiple lists in C#
所以我有一組列表,我有多少列表沒有固定數量。
List1 = {"a", "b", "c", "d"}
List2 = {"b", "c", "d", "e"}
List3 = {"c", "d", "e", "f"}
.
.
.
Listn = {"g", "e", "a", "c"}
每個列表都將包含唯一的項目,並且各個列表的長度可以在 20 - 30 個項目范圍內。 我將所有列表存儲在另一個列表中以允許 n 個列表。
ListOfLists = {List1, List2, List3, ..., Listn}
就使用的最少處理能力而言,生成包含 ListOfLists 中包含的所有唯一項及其出現次數的列表或數組的最佳方法是什么?
就輸出而言,我認為最好的選擇是包含該項目及其出現次數的 arrays 列表。
UniqueListItems = { {"a", 12}, {"b" ,3}, {"c", 18}, {"d", 15}, {"e", 5} }
最終我想按項目出現對列表進行排序,並按降序排列項目。
Output:
c
d
a
e
b
我已經嘗試使用多個嵌套的 for 和 foreach 循環來執行此操作,但結果是一些相當笨拙的代碼。 限制因素之一是我發現的唯一列出操作的列表最多可處理 2 個列表,而不是 n 個列表。
有沒有辦法使用內置的 C# 列表操作來處理 n 個列表? 如果沒有,處理這個問題的最佳方法是什么?
您可以在此處使用Linq
方法,如下面的代碼所示。
var uniqueListItems = ListOfLists.SelectMany(l => l)
.GroupBy(l => l)
.Select(l => new {Key = l.Key, Count = l.Count()})
.OrderByDescending(o => o.Count);
上面的代碼使用SelectMany
來展平列表和結果,查詢應用GroupBy
來計算計數。
您可以在這個 do.net 小提琴上查看示例代碼 - https://do.netfiddle.net/VsByaj
如果您不想使用 LINQ,那么使用Dictionary<string, int>
和枚舉器應該是相當簡單的。
想想這樣的事情:
var list1 = new List<string> { "a", "b", "c" };
var list2 = new List<string> { "a", "b", "c" };
var result = new Dictionary<string, int>();
foreach (var item in GetAllElements(list1, list2))
{
if (result.ContainsKey(item))
{
result[item] = ++result[item];
}
else
{
result[item] = 1;
}
}
private static IEnumerable<string> GetAllElements(params List<string>[] lists)
{
foreach (var list in lists)
{
foreach (var element in list)
{
yield return element;
}
}
}
Dictionary<string, long> counter = new Dictionary<string, long>();
for (int i = 0; i < listOfLists.Count; i++)
{
List<string> list = listOfLists[i];
for (int j = 0; j < list.Count; j++)
{
string value = list[j];
if (counter.ContainsKey(value))
counter[value]++;
else
counter.Add(value, 1);
}
}
用法:
Console.WriteLine($"String abc found {counter["abc"]} times");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.