Remove items from a list with duplicate column values using Linq


If I have a class, say MyClass and it looks like this

public class MyClass
    public int Id { get; set; }
    public string Name { get; set; }
    public string Type { get; set; }

and resulting List data looks like this

1 John primary

2 John secondary

3 Joe primary

4 Jim primary

Can we use Linq to get a list without repeating names where the Type would be chosen depending on it’s value, so if primary and secondary exist we only take the row with primary? If only one row exists per name it does not matter what the value of Type is.

So the final List would look like this

1 John primary

3 Joe primary

4 Jim primary

I could probably create a function to this but would like to know if there’s a more concise way with linq to avoid looping through the list and creating a new list for the output.

>Solution :

This might work:

var output = input.GroupBy(x => x.Name).Select(x => (x.Count() > 1) ? x.FirstOrDefault(y => y.Type == "primary") : x.FirstOrDefault()).ToList();

First, we group by the name. If a group has only one item, it’s fine: Just take the first item of the group. If a group has more than one item, take the first item where the type equals "primary".


Leave a ReplyCancel reply