gpt4 book ai didi

c# - 加入嵌套类的 Csharp linq 选择

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

我有一个名为 school 的 C#class,它有一个类(class)列表(在学校),其中有一个教师列表,其中有一个学生列表,如下所示。我需要得到的是每个包含的老师的所有学生姓名的逗号分隔列表。我怎样才能用linq实现这个目标?完整代码如下:

class LinqTests
{
static void Main(string[] args)
{
Debug.WriteLine("*********************************************************************");

School rw = new School();
for (int j = 0; j < 2; j++)
{
ClassInSchool sr = new ClassInSchool();
for (int i = 0; i < 2; i++)
{
sr.teachers.Add(new Teacher((i % 2), "" + i));
}
rw.classes.Add(sr);
}
var elems = rw.classes.Select(sr => sr.teachers)
.Where(l2s => l2s != null)
.Where(l2s => l2s.Any(l2 => l2.include == true));

Debug.WriteLine(JsonConvert.SerializeObject(elems, Formatting.None));

Debug.WriteLine("*********************************************************************");
}


class School
{
public List<ClassInSchool> classes;
public School()
{
classes = new List<ClassInSchool>();
}
}

class ClassInSchool
{
public List<Teacher> teachers;

public ClassInSchool()
{
teachers = new List<Teacher>();
}
}

class Teacher
{
public bool include;
public List<string> students;
public Teacher(int includeIn, string student)
{
include = Convert.ToBoolean(includeIn);
students = new List<string>();
for (int i = 0; i < 3; i++)
{
students.Add(student + i);
}
}
}
}

最佳答案

    var teachers = rw.classes.Where(x => x.teachers != null)
.SelectMany(x => x.teachers.Where(teacher => teacher.students != null && teacher.include));
var allStudentsNames = teachers.SelectMany(x => x.students);
var uniqueStudentsNames = allStudentsNames.Distinct();
var uniqueStudentsNamesCommSeparatedList = string.Join(", ", uniqueStudentsNames);

您当然可以链接这些方法。

关于c# - 加入嵌套类的 Csharp linq 选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37819842/

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