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

How do I used LINQ to retrieve a distinct list of object X from a list of object Y where object X is stored in a list against object Y

I have a list of objects ("Forms") and each of those objects has it’s own nested list of another object ("Subjects").

My Form object looks like this:

public class Form 
{
    public int Id { get; set; }
    public IEnumerable<Subject>? LinkedSubjects { get; set; }
}

And my nested Subject object looks like this:

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

public class Subject 
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Let’s say I return a list of forms, each of which has its own nested list of linked subjects. One form might be linked to subjects with IDs of 1 and 2, another might be linked to subjects with IDs of 2 and 3, etc.

Using LINQ, how do I select the lists of subjects from this list of forms, combine them, and then remove any duplicates to leave me with a list of distinct subjects?

Thanks!

>Solution :

Not tested, self-explanatory:

var distinctSubjects =
   listOfForms
   .SelectMany( x => x.LinkedSubjects ) // list of subjects
   .GroupBy( x => x.Id ) // grouping by id
   .Select( x => x.First() ) // get first subject from each group

Why to group instead use Distinct ? Because I don’t know if, in your code, is really the same Subject on two forms (if yes, just use Distinct) or is a different object with the same values.

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