2009-01-21 61 views
1

我有多个字符串列表,IList<string>,我想将它们合并到一个列表中,显示每个项目(如字典)的不同字符串和计数。什么是最有效的方式来做到这一点?将列表添加到一起

+0

嗯,我认为这是重复的,但我想这是因为“字典”部分没有。 – 2009-01-21 23:22:00

回答

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; 
    } 
+0

这会比上面的Linq解决方案更快吗? – zsharp 2009-01-22 03:22:41

+0

我认为它应该快一点。但是,您应该基准准确地看到。主要好处是与C#2.0编译器兼容。 – 2009-01-22 09:33:05

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
List<List<string>> source = GetLists(); 
//  
Dictionary<string, int> result = source 
    .SelectMany(sublist => sublist) 
    .GroupBy(s => s) 
    .ToDictionary(g => g.Key, g => g.Count())