我们在项目中使用 Entity Framework 。为了解释我的问题,我将以学生和教授为例。
Assumption: There can be multiple students under one professor but each student has only professor assigned.
首先,我将从
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();
我想知道,在这种情况下哪种方法最好:创建列表的字典? 为什么?
最佳答案
在我看来,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()
});
关于c# - 使用 Linq 创建对象列表与创建字典的性能比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21935578/