Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove duplicate items from list in c#

Tags:

c#

linq

I have list of class of type

public class MyClass
{        
    public SomeOtherClass classObj;         
    public string BillId;           
}

public List<MyClass> myClassObject;

Sample Values:

BillId = "123",classObj = {},
BillId = "999",classObj = {},
BillId = "777",classObj = {},
BillId = "123",classObj = {}

So in above example, we have duplicate values for BillId. I would like to remove all the duplicate values (Not Distinct) so the result would contain only 999 & 777 value.

One way to achieve this to

  • Loop through all items
  • Get count of unique BillId
  • If count is greater than 1, store that BillId in another variable
  • Loop again and remove item based on BillId

Is there any straightforward way to achieve this?

like image 854
Shaggy Avatar asked Jun 21 '17 15:06

Shaggy


People also ask

How do you remove duplicate objects from an array?

Array. filter() removes all duplicate objects by checking if the previously mapped id-array includes the current id ( {id} destructs the object into only its id). To only filter out actual duplicates, it is using Array.


1 Answers

I think this would work:

var result = myClassObject.GroupBy(x => x.BillId)
    .Where(x => x.Count() == 1)
    .Select(x => x.First());

Fiddle here

like image 56
maccettura Avatar answered Sep 20 '22 13:09

maccettura