Gun
Gun

Reputation: 1411

How to Group the elements within group in Linq

I have an Employee Collection and i want to filter in such a way that first 2 columns only should be filtered and the third column values should be appended and the final result should be in a single row

The below is my code

List<Employe> Employeecollection = new List<Employe>();

        Employeecollection.Add(new Employe("Employee1", "Dept1","Language1"));
        Employeecollection.Add(new Employe("Employee2", "Dept2", "Language2"));
        Employeecollection.Add(new Employe("Employee3", "Dept3", "Language3"));
        Employeecollection.Add(new Employe("Employee3", "Dept3", "Language3"));
        Employeecollection.Add(new Employe("Employee1", "Dept1", "Language2"));

        foreach (Employe item in Employeecollection.GroupBy(x => new { fName = x.EmpName, lName = x.EmpDept, mName = x.KnownLanguages }).Select(g => g.First()))
        {
            Console.WriteLine(item.EmpName + "   " + item.EmpDept + " " + item.KnownLanguages);
        }

but i would like to display the results like below

Employee1 Dept1 Language1,Language2
Employee2 Dept2 Language2
Employee3 Dept3 Language3

Upvotes: 1

Views: 76

Answers (2)

Servy
Servy

Reputation: 203829

You don't want to group on KnownLanguages. It shouldn't be included in your group selector. The group selector should select all of thing that you want to be the same for all items in a group.

You also need to change how you print your results. Get the common values for each of the items in a group through the Key, and the other values through iterating the group itself.

var query = Employeecollection.GroupBy(x => new
{
    x.EmpName,
    x.EmpDept
};

foreach (var group in query)
{
    string languages = string.Join(", ", 
        group.Select(employee => employee.KnownLanguages)
        .Distinct());
    Console.WriteLine(group.Key.EmpName + "   " + group.Key.EmpDept + " " 
        + languages;
}

Upvotes: 2

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

Group employees by name and department, then select joined string of known languages for each employee:

from e in Employeecollection
group e by new { e.Name, e.EmpDept } into g
select new {
   g.Key.Name,
   g.Key.EmpDept,
   Languages = String.Join(",", g.Select(x => x.KnownLanguages))
}

If you want results as single row, then do following projection instead:

select String.Format("{0} {1} {2}", 
    g.Key.Name, g.Key.EmpDept, String.Join(",", g.Select(x => x.KnownLanguages)))

BTW I think its a weird property name KnownLanguages for property which holds single language

Upvotes: 5

Related Questions