Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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".

Online-demo: https://dotnetfiddle.net/fAwK4Y

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading