从集合+ linq + C#中的泛型集合分配给泛型集合

时间:2010-08-06 02:03:20

标签: c# linq

我在StudentCollection类中有一个Student的Generic集合,每个Student Class都有一个SubjectCollection类。

我有一个返回StudentCollection的方法。如何直接从StudentCollection获取SubjectCollection?

我找到了两种方法 -

第一种方式

        StudentSubjectCollection studentsubjectCollection = new StudentSubjectCollection();
        var studentsColl = GetAllStudentCollection();
        foreach (var subject in studentsColl )
        {
            studentsubjectCollection = subject.StudentSubjectCollection;
        }

第二种方式

        StudentSubjectCollection studentsubjectCollection = new StudentSubjectCollection();
        StudentCollection studentColl = GetAllStudentCollection();
        foreach (MessageModule messageModule in messageModuleCollection)
        {
          studentsubjectCollection.AddRange(messageModule.MessageModuleReplyCollection);   
        }

是否有其他方法可以执行此操作,例如一行代码直接从StudentCollection获取StudentSubjectCollection。

类似于StudentSubjectCollection studentsubjectColl = GetAllStudentCollection()。选择(field => field .....);但这不起作用。

由于 --Vinay

1 个答案:

答案 0 :(得分:1)

var students = GetAllStudentCollection();
var subjects = students.SelectMany(stu=>stu.StudentSubjectCollection);