Fastest way to find common items across multiple lists in C#

后端 未结 11 2020

Given the following:

List> optionLists;

what would be a quick way to determine the subset of Option objects that a

11条回答
  •  佛祖请我去吃肉
    2021-01-19 03:06

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

提交回复
热议问题