Given the following:
List> optionLists;
what would be a quick way to determine the subset of Option objects that a
You can do this by counting occurrences of all items in all lists - those items whose occurrence count is equal to the number of lists, are common to all lists:
static List FindCommon(IEnumerable> lists)
{
Dictionary map = new Dictionary();
int listCount = 0; // number of lists
foreach (IEnumerable list in lists)
{
listCount++;
foreach (T item in list)
{
// Item encountered, increment count
int currCount;
if (!map.TryGetValue(item, out currCount))
currCount = 0;
currCount++;
map[item] = currCount;
}
}
List result= new List();
foreach (KeyValuePair kvp in map)
{
// Items whose occurrence count is equal to the number of lists are common to all the lists
if (kvp.Value == listCount)
result.Add(kvp.Key);
}
return result;
}