2
我们在我们的项目中使用实体框架。为了解释我的问题,我将以学生和教授为例。使用Linq创建对象列表与创建字典的性能比较?
假设:一名教授可以有多名学生,但每名 学生只有教授分配。
首先,我会找到的
Student
的名单不同的ID。List<int> profIds= students.Select(s => s.profId).Distinct();
然后我尝试更新下的教授,他是做工程的名义,我已经有
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();
我想知道,哪一种方法最好是在这种情况下:创建列表的字典? 为什么?
你想用你的结果在哪里? – Christos
这是*你的*应用程序,当然是由你来决定哪种方法最好?如果你想知道哪种方法更快,你有数据,基准... – James
@Christos我想使用报告的结果。以上代码是RDL报告直接调用的Service/DAL方法的一部分。 – kushdilip