我有一系列的清单:
var stringLists = new List<string>[] { new List<string>(){ "a","b","c" },new List<string>(){ "d",new List<string>(){ "a","d","c" } };
我想提取至少2个列表中常见的所有元素.所以对于这个例子,我应该得到所有元素[“a”,“b”,“c”,“d”].我知道如何找到所有共同的元素,但却想不出任何解决这个问题的方法.
解决方法
你可以使用这样的东西:
var result = stringLists.SelectMany(l => l.Distinct()) .GroupBy(e => e) .Where(g => g.Count() >= 2) .Select(g => g.Key);
只是为了好玩一些迭代解决方案:
var seen = new HashSet<string>(); var current = new HashSet<string>(); var result = new HashSet<string>(); foreach (var list in stringLists) { foreach(var element in list) if(current.Add(element) && !seen.Add(element)) result.Add(element); current.Clear(); }
要么:
var already_seen = new Dictionary<string,bool>(); foreach(var list in stringLists) foreach(var element in list.Distinct()) already_seen[element] = already_seen.ContainsKey(element); var result = already_seen.Where(kvp => kvp.Value).Select(kvp => kvp.Key);
或(灵感来自Tim’s answer):
int tmp; var items = new Dictionary<string,int>(); foreach(var str in stringLists.SelectMany(l => l.Distinct())) { items.TryGetValue(str,out tmp); items[str] = tmp + 1; } var result = items.Where(kv => kv.Value >= 2).Select(kv => kv.Key);