2014-02-21 52 views
2

我们在我们的项目中使用实体框架。为了解释我的问题,我将以学生和教授为例。使用Linq创建对象列表与创建字典的性能比较?

假设:一名教授可以有多名学生,但每名 学生只有教授分配。

  1. 首先,我会找到的Student的名单不同的ID。

    List<int> profIds= students.Select(s => s.profId).Distinct(); 
    
  2. 然后我尝试更新下的教授,他是做工程的名义,我已经有IEntityRepository<Professor>profesors对象。这一步我有两种可选的方法。

第一:

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

二:

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

我想知道,哪一种方法最好是在这种情况下:创建列表的字典? 为什么?

+0

你想用你的结果在哪里? – Christos

+0

这是*你的*应用程序,当然是由你来决定哪种方法最好?如果你想知道哪种方法更快,你有数据,基准... – James

+0

@Christos我想使用报告的结果。以上代码是RDL报告直接调用的Service/DAL方法的一部分。 – kushdilip

回答

0

听起来好像一个GroupBy条款是更好地在这里适合

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