You can use Dictionary<string, int> , the key is a string, and the value is count:
Dictionary<string, int> itemCounts = new Dictionary<string,int>(); for(int i = 0; i < stringLists.Length; i++) { List<string> list = stringLists[i]; foreach(string str in list.Distinct()) { if(itemCounts.ContainsKey(str)) itemCounts[str] += 1; else itemCounts.Add(str, 1); } } var result = itemCounts.Where(kv => kv.Value >= 2);
I am using list.Distinct() since you only want to count entries in different lists.
As requested, this is an extension method that can be reused with any type:
public static IEnumerable<T> GetItemsWhichOccurAtLeastIn<T>(this IEnumerable<IEnumerable<T>> seq, int minCount, IEqualityComparer<T> comparer = null) { if (comparer == null) comparer = EqualityComparer<T>.Default; Dictionary<T, int> itemCounts = new Dictionary<T, int>(comparer); foreach (IEnumerable<T> subSeq in seq) { foreach (T x in subSeq.Distinct(comparer)) { if (itemCounts.ContainsKey(x)) itemCounts[x] += 1; else itemCounts.Add(x, 1); } } foreach(var kv in itemCounts.Where(kv => kv.Value >= minCount)) yield return kv.Key; }
The use is simple:
string result = String.Join(",", stringLists.GetItemsWhichOccurAtLeastIn(2));
source share