简体   繁体   中英

Get the count of distinct elements from a list of lists using 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();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM