Presi
Presi

Reputation: 827

Remove duplicates from list but keep one and edit it

I have a List which can contain duplicates. So because of that reason I want to delete all the duplicates. I know, that I can do this with the Distinct() Method like this:

myList.Distinct().ToList();

But I have to edit the item in the list, which was the one don't removed from Distinct().

Example: myList looks like this:

(1,'A', "Normal"),
(2,'B', "Normal"),
(3,'A', "Normal"),
(4,'C', "Normal"),
(5,'C', "Normal"),
(6,'A', "Normal");

And the result of this should be following:

(1,'A', "Multiple"),
(2,'B', "Normal"),
(4,'C', "Multiple")

Edit:

I also know, that I can do it with GroupBy. Then I also have all items only one time in my list:

myList.GroupBy(x => x.Letter).Select(x => x.First()).ToList();

Upvotes: 2

Views: 618

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62498

you can use linq to group them and then project by putting condition that if the grouped rows count is 1 then it is normal otherwise it's multiple something like:

var result = list.GroupBy(x => new 
                           { 
                             ID = x.Id, 
                            Text= x.Letter
                         })
                 .Select(x => new Model() 
                             { 
                                ID = x.Key.ID,
                                Letter = x.Key.Letter
                                Type = (x.Count() == 1 ? "Normal" : "Multiple")  
                              });

Revised (this only checks duplicates based on Letter only but not Id):

var result = list.GroupBy(x => x.Letter)
                 .Select(x => new Model() 
                             { 
                                ID = x.First().Id,
                                Letter = x.Key
                                Type = (x.Count() == 1 ? "Normal" : "Multiple")  
                              });

Assuming your class looks like:

public class Model
{
       public int ID {get;set;}
       public string Letter {get;set;}
       public string Type {get;set;}
}

Upvotes: 7

Related Questions