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