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

前端 未结 8 1945
无人及你
无人及你 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:37

    var duplicates = from car in cars
                     group car by car.Color into grouped
                     from car in grouped.Skip(1)
                     select car;
    

    This groups the cars by color and then skips the first result from each group, returning the remainder from each group flattened into a single sequence.

    If you have particular requirements about which one you want to keep, e.g. if the car has an Id property and you want to keep the car with the lowest Id, then you could add some ordering in there, e.g.

    var duplicates = from car in cars
                     group car by car.Color into grouped
                     from car in grouped.OrderBy(c => c.Id).Skip(1)
                     select car;
    

提交回复
热议问题