Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove objects with a duplicate property from List

Tags:

arrays

c#

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 new List) where there is only one object per ID property?

[Any additional duplicates are dropped out of the List]

like image 272
Baxter Avatar asked Apr 03 '12 12:04

Baxter


People also ask

How do I remove duplicates from a sharepoint list?

Remove only the duplicatesUse the skip(…) expression to skip the first item and loop through the rest in another 'Apply to each'. Then just delete all the remaining items using their ID. At the end of the flow you'll have only the unique items in the list.


2 Answers

If you want to avoid using a third-party library, you could do something like:

var bar = fooArray.GroupBy(x => x.Id).Select(x => x.First()).ToList(); 

That will group the array by the Id property, then select the first entry in the grouping.

like image 153
Daniel Mann Avatar answered Sep 30 '22 12:09

Daniel Mann


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

like image 32
sll Avatar answered Sep 30 '22 14:09

sll