我有多个字符串列表IList<string>
,我想在一个列表中合并,显示每个项目的不同字符串和计数(如字典)。这样做最有效的方法是什么?
答案 0 :(得分:3)
LINQ(在键入和维护的代码方面肯定是最有效的;整体性能约与任何其他方法相同):
如果列表是单独的变量:
var qry = from s in listA.Concat(listB).Concat(listC) // etc
group s by s into tmp
select new { Item = tmp.Key, Count = tmp.Count() };
如果列表全部在列表的父列表中:
var qry = from list in lists
from s in list
group s by s into tmp
select new { Item = tmp.Key, Count = tmp.Count() };
然后,如果你真的想要一个清单:
var resultList = qry.ToList();
答案 1 :(得分:1)
Dictionary<string, int> count = new Dictionary<string, int>();
foreach(IList<int> list in lists)
foreach(int item in list) {
int value;
if (count.TryGetValue(item, out value))
count[item] = value + 1;
else
count[item] = 1;
}
答案 2 :(得分:1)
List<List<string>> source = GetLists();
//
Dictionary<string, int> result = source
.SelectMany(sublist => sublist)
.GroupBy(s => s)
.ToDictionary(g => g.Key, g => g.Count())