繁体   English   中英

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

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

你快到了:

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.

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