C# 3.0: Need to return duplicates from a List<>

前端 未结 8 1907
无人及你
无人及你 2020-12-23 19:05

I have a List<> of objects in C# and I need a way to return those objects that are considered duplicates within the list. I do not need the Distinct resultset, I need a

8条回答
  •  遥遥无期
    2020-12-23 19:51

    IEnumerable GetDuplicateColors(List cars)
    {
        return cars.Where(c => cars.Any(c2 => c2.Color == c.Color && cars.IndexOf(c2) < cars.IndexOf(c) ) );
    }    
    

    It basically means "return cars where there's any car in the list with the same color and a smaller index".

    Not sure of the performance, though. I suspect an approach with a O(1) lookup for duplicates (like the dictionary/hashset method) can be faster for large sets.

提交回复
热议问题