gpt4 book ai didi

c# - 在 C# 中将 foreach 转换为 lambda 表达式

转载 作者:太空宇宙 更新时间:2023-11-03 23:09:12 24 4
gpt4 key购买 nike

我刚开始使用 lambda 表示法,所以如果我错了,请纠正我的理解。是否可以使用 lambda 在一个语句中为每个循环重写 a?我有以下内容:

模型

public partial class Section
{
public int SectionID { get; set; }
public List<Question> questions { get; set; }
//...
}

public partial class Question
{
public int QuestionID { get; set; }
public int SectionID { get; set; }
//...
}

前缘

List<Section> sections = db.getSections.ToList();
List<Question> questions = db.getQuestions.ToList();

foreach (var section in sections)
{
List<Question> questionsInSection = new List<Question>();
foreach (var question in questions)
{
if(section.SectionID == question.SectionID)
questionsInSection.Add(question);
}
section.Questions = questionsInSection;
}

最佳答案

List<Section> sections = questions
.GroupBy(x=>x.SectionID)
.Select(x=>new Section(){SectionID=x.Key,questions=x.ToList()})
.ToList()

关于c# - 在 C# 中将 foreach 转换为 lambda 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40049974/

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