c# and LINQ - convert IGrouping to List

11,323

Looking at your code it seems that what you are trying to achieve is to get the list of people that exist in each list. If so, you can use the following query:

var query = setOfPersons
    .SelectMany(l => l.Select(l1 => l1))
    .GroupBy(p => p.Id)
    .Where(g => g.Count() == setOfPersons.Count)
    .Select(x=>x.First())             // Select first person from the grouping - they all are identical
    .ToList();

Console.WriteLine("These people appears in all set:");

foreach (var a in query)
{
    Console.WriteLine("Id: {0} Name: {1}", a.Id, a.Name);
}

Here you select just a single item from each grouping, because they all are identical.

Share:
11,323
nidarshani fernando
Author by

nidarshani fernando

Updated on July 23, 2022

Comments

  • nidarshani fernando
    nidarshani fernando almost 2 years

    I have the following code written to find common objects in a list of objects

    https://dotnetfiddle.net/gCgNBf

    ..............................

    var query = setOfPersons
                .SelectMany(l => l.Select(l1 => l1))
                .GroupBy(p => p.Id)
                .Where(g => g.Count() == setOfPersons.Count);
    

    After that, I need to convert "query" to a list of "Person" objects ( List ) to achieve something else.

    I tried using "ToList()"... But it says:

    " cannot convert IGrouping to a List ".

    Can someone help me to fix it ?

  • nidarshani fernando
    nidarshani fernando about 9 years
    I don't know how to thank you enough ! you saved my day ! Thanx a million !