使用LINQ从列表列表中获取不同元素的数量

我有一个列表列表的结构。下面是示例:

学生桌

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

我需要获得不同的HouseZipCode,学生人数也要相同。

下面的代码不起作用:

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();
cg990942 回答:使用LINQ从列表列表中获取不同元素的数量

您快到了:

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();
本文链接:https://www.f2er.com/3167683.html

大家都在问