【发布时间】:2014-02-21 21:46:51
【问题描述】:
我们在项目中使用实体框架。为了解释我的问题,我将以学生和教授为例。
假设:一位教授下可以有多个学生,但每个 学生只分配了教授。
-
首先,我将从
Student的列表中找到不同的 ID。List<int> profIds= students.Select(s => s.profId).Distinct(); 然后我尝试更新他正在做项目的教授的名字,我已经有
profesors类型的IEntityRepository<Professor>对象。这一步我有两种替代方法。
第一:
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 我想将结果用于报告。以上代码是 RDL 报告将直接调用的 Service/DAL 方法的一部分。
标签: c# performance linq entity-framework-4