2014-02-21 53 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() 
    });