gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:50:56 25 4
gpt4 key购买 nike

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

学生表

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

关于c# - 使用 LINQ 从列表列表中获取不同元素的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58691105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com