Home > front end >  Combine duplicated items in a list - c#
Combine duplicated items in a list - c#

Time:12-22

Similar to remove duplicate items from list in c#

I want to create a list then if a list item appears more than once, only treat it as one item, not duplicating it in the list and not ignoring it either.

Using the example from the ticket above: https://dotnetfiddle.net/NPqzne

List<MyClass> list = new List<MyClass>();

list.Add(new MyClass() { BillId = "123", classObj = {} });
list.Add(new MyClass() { BillId = "777", classObj = {} });
list.Add(new MyClass() { BillId = "999", classObj = {} });
list.Add(new MyClass() { BillId = "123", classObj = {} });

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

Console.WriteLine(string.Join(", ", result.Select(x => x.BillId)));

How would I change that so results are

123, 777, 999 

rather than ignoring 123 all together because its a duplicate?

CodePudding user response:

you can modify to these lines in your code, I have tried with your dotnetfiddle code. its working as expected.

var result = list.Select(x => x.BillId).Distinct();
Console.WriteLine(string.Join(", ", result.Select(x => x)));

You need to use Distinct to get the unique values.

Thank you for providing dotnetfiddle link, it helped in writing code easily.

CodePudding user response:

Starting from .Net 6 you can try DistinctBy:

var result = myClassObject
  .DistinctBy(x => x.BillId)
  .ToList();

On older versions you can modify your current GroupBy solution (your don't want filtering .Where(x => x.Count() == 1) - we are not ignoring duplicatesm which have Count() > 1):

var result = myClassObject
  .GroupBy(x => x.BillId)
  .Select(x => x.First())
  .ToList();

Finally, no Linq solution with a help of HashSet<string>:

var result = new List<myClassObject>();

var unique = new HashSet<string>();

foreach (var item in myClassObject)
  if (unique.Add(item.BillId))
    result.Add(item);

CodePudding user response:

You could use a Dictionary or HashSet instead of List, since these collection types don't allow duplicates:

Dictionary<string, MyClass> dict = new Dictionary<string, MyClass>(); 
dict.Add(123, new MyClass() { BillId = "123", classObj = {} }); 
dict.Add(777, new MyClass() { BillId = "777", classObj = {} }); 
dict.Add(999, new MyClass() { BillId = "999", classObj = {} }); 

dict.Add(123, new MyClass() { BillId = "123", classObj = {} }); // this //will not be added as the key is already present in the dictionary

var result = dict.Select(x => x.Value); Console.WriteLine(string.Join(", ", result.Select(x => x.BillId))); //123,777, 999

  • Related