Home > Mobile >  Group a database data by some properties
Group a database data by some properties

Time:08-05

i would like to group some data given by a database by an Id like so:

Suppose list A is like this:

Id: Description: Status:
1   Desc1        1
2   Desc2        2
1   Desc3        2  
3   Desc4        1
3   Desc5        2 

Using LINQ how can i get a list like this one: (i suppose i have to use GroupBy?)

List A sorted or grouped

Id: Description:
1   [Desc1, Desc3]
2   Desc2
3   [Desc4, Desc5]

CodePudding user response:

Use .GroupBy() with Id as key. And return a list of object(s) with Id and Description with an array of strings.

Method syntax

var result = input.GroupBy(x => x.Id)
            .Select(x => new
            {
                Id = x.Key,
                Description = x.Select(y => y.Description).ToList()
            })
            .ToList();

Or

Query syntax

var result = (from x in input
                group x by x.Id into g
                select new
                {
                    Id = g.Key,
                    Description = g.Select(y => y.Description).ToList()
                }
            ).ToList();

The above result returns list of anonymous object(s). Or map the result to your model class insted of using anonymous.

.NET Fiddle Demo

  • Related