Csharp linq选择加入嵌套类

时间:2016-06-14 18:45:45

标签: c# linq lambda

我有一个名为school的C#课程,其中有一个班级列表(在学校),其中有一个教师列表,其中包含如下学生列表。我需要得到的是每个包含的老师的所有学生姓名的逗号分隔列表。我怎样才能用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);
            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

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

您当然可以将这些方法联系起来。

答案 1 :(得分:1)

如果你想要学生,我认为你想要以下

var students = rw.classes
    .SelectMany(c => c.teachers)
    .Where(t => t.include)
    .SelectMany(t => t.students);

然后得到一个逗号分隔的字符串

var csv = string.Join(", ", students);

我已经删除null列表上的teachers检查,因为您正在ClassInSchool构造函数中对其进行初始化。但是,如果您需要防范可能的null集合,则可以改为执行此操作。

var students = rw.classes
    .Where(c => c.teachers != null)
    .SelectMany(c => c.teachers)
    .Where(t => t.include && t.students != null)
    .SelectMany(t => t.students);