Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get properties in LINQ inside group by clause

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading