Search code examples
c#listlinqunique

Remove duplicate items from list in C#, according to one of their properties


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?


Solution

  • I think this would work:

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

    Fiddle here