Search code examples
c#linqlinq-to-entities

How to use LINQ group by with where clause


I have a list with data as mentioned below:

From        To      Gender    departure date
Delhi      Mumbai    M         16-Feb-18
Delhi      Mumbai    M         16-Feb-18
Delhi      Mumbai    F         16-Feb-18
Delhi      Mumbai    C         16-Feb-18
Mumbai     Mohili    F         16-Feb-18
Mumbai     Mohili    M         16-Feb-18
Mumbai     Mohili    C         16-Feb-18

I want to group this list based on From and To columns and calculate how many male, female and child are there in each group though LINQ. How can I do this. I grouped it like this but now how to calculate count of male and female.

var list = result.Journey.GroupBy(x => new { x.From, x.To });

Solution

  • Try below code,

            var list = travelars.GroupBy(x => new { x.From, x.To }).ToList().Select(e => new { 
                MaleCount = e.Count(g => g.Gender == "M"),
                FemaleCount = e.Count(g => g.Gender == "F"),
                ChildCount = e.Count(g => g.Gender == "C"),
            });