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

后端 未结 11 1963

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

    After searching the 'net and not really coming up with something I liked (or that worked), I slept on it and came up with this. My SearchResult is similar to your Option. It has an EmployeeId in it and that's the thing I need to be common across lists. I return all records that have an EmployeeId in every list. It's not fancy, but it's simple and easy to understand, just what I like. For small lists (my case) it should perform just fine—and anyone can understand it!

    private List GetFinalSearchResults(IEnumerable> lists)
    {
        Dictionary oldList = new Dictionary();
        Dictionary newList = new Dictionary();
    
        oldList = lists.First().ToDictionary(x => x.EmployeeId, x => x);
    
        foreach (List list in lists.Skip(1))
        {
            foreach (SearchResult emp in list)
            {
                if (oldList.Keys.Contains(emp.EmployeeId))
                {
                    newList.Add(emp.EmployeeId, emp);
                }
            }
    
            oldList = new Dictionary(newList);
            newList.Clear();
        }
    
        return oldList.Values.ToList();
    }
    

提交回复
热议问题