Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the count of distinct elements from a list of lists using LINQ

Tags:

c#

linq

I have a structure which is a list of list. Below is the example :

Student Table

public partial class Students
{
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
        public int Marks { get; set; }
        public virtual ICollection<StudentAddresses> StudentAddresses{ get; set; }
}

public partial class StudentAddresses
{
    public string HouseArea {get; set;}
    public string HouseCity {get; set;}
    public string HouseZipCode {get; set;}
}

var student = context.Students
              .Include(i => i.StudentAddresses)
              .Where(c => c.Marks > 50);

I need to get distinct HouseZipCode and the student counts for the same.

The below code is not working:

var test = student.GroupBy(g => g.StudentAddresses.Select(gs => gs.HouseZipCode ))
    .Select(s => new StudentModel { ZipCode= s.Key, StudentNumbers = s.Count() })
    .OrderBy(o => o.HouseZipCode )
    .ToList();
like image 424
TheFallenOne Avatar asked Oct 15 '25 13:10

TheFallenOne


1 Answers

You are almost there:

var test = student
    .SelectMany(s => s.StudentAddresses) // get all addresses from students
    .GroupBy(adr => adr.HouseZipCode) // group addresses by zip code
    .Select(grp => new StudentModel { ZipCode= grp.Key, StudentNumbers = grp.Count() }) // count how many addresses have same zip code
    .OrderBy(o => o.ZipCode)
    .ToList();
like image 107
Euphoric Avatar answered Oct 18 '25 09:10

Euphoric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!