سؤال

We are using Entity framework in our project. To Explain my question, I will take example of Students and Professors.

Assumption: There can be multiple students under one professor but each student has only professor assigned.

  1. First I will find distinct Ids from List of Student's.

    List<int> profIds= students.Select(s => s.profId).Distinct();
    
  2. Then I try to update the name of professor under which he is doing project, I already have profesors object of type IEntityRepository<Professor> . I have two alternative approaches for this step.

First:

Dictionary<int, string> profDictionary = professors.SearchFor(x => 
        profIds.Contains(x.Id))
       .ToDictionary(p => p.Id, p => 
          string.Format("{0} {1} {p.FirstName,p.LastName));

foreach(var stu in students)
        stu.ProfName = profDictionary[stu.profId];

Second:

profList = professors.SearchFor(profIds.Contains(x.Id))
                .Select(item => new ProfessorDTO()
                {
                    Id= item.Id,
                    FirstName = item.FirstName,
                    LastName = item.LastName
                }).ToList();

foreach(var stu in students)
        stu.ProfName = profList.Where(x => x.id == stu.profId).Select(x => 
             string.Format("{0} {1}", x.FirstName, x.LastName)).FirstOrDefault();

I want to know, Which approach is best in this case: Creating a dictionary of a List? And Why?

هل كانت مفيدة؟

المحلول

Sounds to me like a GroupBy clause would be better suited here

var studentsByProfessor = students.GroupBy(x => x.profId)
    .Select(g => new
    {
        ProfName = professors.FirstOrDefault(x => x.id == g.Key)
            .Select(x => string.Format("{0} {1}", x.FirstName, x.LastName)),
        Students = g.ToList()
    });
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top