Remove objects with a duplicate property from List

后端 未结 4 559
陌清茗
陌清茗 2021-02-04 23:03

I have a List of objects in C#. All of the objects contain a property ID. There are several objects that have the same ID property.

How can I trim the List (or make a

4条回答
  •  北荒
    北荒 (楼主)
    2021-02-04 23:32

    MoreLINQ DistinctBy() will do the job, it allows using object proeprty for the distinctness. Unfortunatly built in LINQ Distinct() not flexible enoght.

    var uniqueItems = allItems.DistinctBy(i => i.Id);
    

    DistinctBy()

    Returns all distinct elements of the given source, where "distinctness" is determined via a projection and the default eqaulity comparer for the projected type.

    • Download MoreLINQ
    • DistinctBy() sources

    PS: Credits to Jon Skeet for sharing this library with community

提交回复
热议问题