[英]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.我需要获得不同的 HouseZipCode 并且学生人数相同。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.