Vinay
Vinay

Reputation: 221

assign to a generic collection from a generic collection inside collection + linq + C#

I have a Generic collection of Student in StudentCollection Class and each Student Class is having a SubjectCollection Class.

I have a method which returns the StudentCollection.How can I get the SubjectCollection directly from the StudentCollection ?

I found two ways of doing it---

First Way

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

Second Way

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

Is there any other way of doing this such as one line of code to get the StudentSubjectCollection directly from the StudentCollection.

Something like StudentSubjectCollection studentsubjectColl = GetAllStudentCollection().Select(field=> field.....); but this doesnt work.

Thanks --Vinay

Upvotes: 0

Views: 142

Answers (1)

Cheng Chen
Cheng Chen

Reputation: 43523

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

Upvotes: 1

Related Questions