Sumit Deshpande
Sumit Deshpande

Reputation: 2155

C# Linq To Create Group On Multiple Properties and format the resultant group into single key/property?

I have following scenario where I want to find duplicates after forming the group and realign/format the duplicate data with some common class.

Example -

var lst = new List<Test> 
{ 
    new Test{Category="A",Class="Class1",Id="101",Name="John"},
    new Test{Category="B",Class="Class2",Id="102",Name="Peter"},
    new Test{Category="A",Class="Class2",Id="103",Name="David"},
    new Test{Category="C",Class="Class3",Id="104",Name="Julia"},
    new Test{Category="D",Class="Class4",Id="105",Name="Ken"},
    new Test{Category="A",Class="Class1",Id="106",Name="Robert"},
};

I have created the group as -

var group = 
    from c in lst
    group c by new
    {
        c.Category,
        c.Class
    } into g
    select new
    {
        Category = g.Key.Category,
        Class = g.Key.Class,
        Id = lst.Where(x => g.Key.Category == x.Category && g.Key.Class==x.Class)
                .Select(y => y.Id).ToList()
    };

Which results me 2 group items for Category A with different Classes -

GroupItem1 - Category = "A" , Class = "Class1", Id = {101,106}
GroupItem2 - Category = "A" , Class = "Class2", Id = {103}

So I have requirement to show result in such case as below with other categories as -

Category = "A", Class = "Class1 OR SomeCommonClass", Id = {101,106,103}

Is it possible to achieve this result with minimum code and optimized logic.

Upvotes: 0

Views: 76

Answers (3)

Ayaz
Ayaz

Reputation: 2121

            var group = lst.GroupBy(l => l.Category)
                .Select(x => new
                {
                    Category = x.Key,
                    Class = string.Join(" OR ", x.Select(c => c.Class).Distinct()),
                    Ids = x.Select(c => c.Id).ToList()
                }).ToList();

Upvotes: 1

NetMage
NetMage

Reputation: 26917

Replace your group query with this:

var groups =
    from c in lst
    group c by c.Category into g
    select new { Category = g.Key, Class = g.Select(c => c.Class).Distinct().Join(" or "), IDs = g.Select(c => c.Id).ToList() };

where Join is an IEnumerable extension method:

public static string Join(this IEnumerable<string> strings, string sep) => String.Join(sep, strings.ToArray());

Upvotes: 1

Gun
Gun

Reputation: 1411

If you want to group by Category and get the result below is the query.

            var group =
                from c in lst
                group c by new
                {
                    c.Category

                } into g
                select new
                {
                    Category = g.Key.Category,
                    Class = lst.Where(x => g.Key.Category == x.Category).Select(y => y.Class).ToList(),
                    Id = lst.Where(x => g.Key.Category == x.Category)
                            .Select(y => y.Id).ToList()
                };

Upvotes: 1

Related Questions