convert foreach to lambda expression in C#

c# entity-framework-6 lambda

Accepted Answer

There was a prior response that was posted but was removed... What I was attempting to do is achieved by this solution in a single sentence.

sections.ForEach(s => { s.Questions = questions.Where(q => q.SectionID == s.SectionID).ToList(); });
10/14/2016 7:54:15 PM

Popular Answer

I believe you are using Entity Framework; in that case, put the value to Navigational Features and simply:

var sections = db.getSections.Include(s => s.Questions)

Check One-to-Many Relationship Configuration to see whether this is a one-to-many connection.

If you don't employ Entity Framework,GroupJoin project a fresh image onto the two tables.Section :

var result = (from section in db.getSections
              join question in db.getQuestion 
              on section.SectionID == questions.SectionID into sectionQuestions
              select new Section
                  Prop1 = section.Prop1,
                  Prop2 = section.prop2,
                  Questions = sectionQuestions

If you decide not to utilise the Navigation Properties or build a new page for whatever reason,Section if you want to utilise the foreach function and your data is large, follow these steps:

var sections = db.getSections.ToList();
var questions = db.getQuestions.GroupBy(item => item.SectionID)
                               .ToDictionary(key => key.Key,
                                             value => value.Select(i => i).ToList());

foreach (var section in sections)
    List<Question> selectedQuestions;
    if (efficientQuestions.TryGetValue(section.SectionID, out selectedQuestions))
        section.Questions = selectedQuestions;

why I created thisforeach more difficult, thus the queries are kept in a dictionary with the key being theSectionID This reduces the complexity ofo(n) but noto(n)2 (As when usingforeach + Where )

However, as you can see from all theif in the justification. Without a doubt, using navigation properties is the best choice.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow