Home > Mobile >  Get properties in LINQ inside group by clause
Get properties in LINQ inside group by clause

Time:04-20

I'm new to LINQ and I'm trying to group a list by two columns and use the count aggregate function but I'm not sure how to write this query properly.

Here is my class

public class Result
    { 
        public string? Type { get; set; }
        public int Age { get; set; }
        public string? Name { get; set; }
        public string? Description { get; set; }
        public int Count { get; set; }
    }

First I read some data from a dataTable and add it to a list of Result without Count property

List<Result> list = new();
foreach (DataRow row in dataTable.Rows)
    {
    list.Add(new Result
                {
                    Type =row["Type"].ToString(),
                    Age = int.Parse(row["Age"].ToString()),
                    Name = row["Name"].ToString(),
                    Description = row["Description"].ToString(),
                });
    }

Now I want to group by Age and Type, I wrote this query and it returns the right result but I'm wondering if there is another cleaner way to write this instead of using Select().FirstOrDefault() ?

IEnumerable<Result> myResult = list.GroupBy(x => new { x.Age, x.Type }).Select(gr =>
             new Result
             {
                 Age = gr.Key.Age,
                 Type = gr.Key.Type,
                 Name = gr.Select(x => x.Name).FirstOrDefault(),
                 Description = gr.Select(x => x.Description).FirstOrDefault(),
                 Count = gr.Count()
             }).ToList();

CodePudding user response:

You can try to use FirstOrDefault()?. to make it simple which use Null-conditional

IEnumerable<Result> myResult = list.GroupBy(x => new { x.Age, x.Type }).Select(gr =>
     new Result
     {
         Age = gr.Key.Age,
         Type = gr.Key.Type,
         Name = gr.FirstOrDefault()?.Name,
         Description = gr.FirstOrDefault()?.Description,
         Count = gr.Count()
     }).ToList();
  • Related