c# - 使用 Linq 创建对象列表与创建字典的性能比较?

标签 c# performance linq entity-framework-4

我们在项目中使用 Entity Framework 。为了解释我的问题,我将以学生和教授为例。

Assumption: There can be multiple students under one professor but each student has only professor assigned.

  1. 首先,我将从 Student 的列表中找到不同的 ID的。

    List<int> profIds= students.Select(s => s.profId).Distinct();
    
  2. 然后我尝试更新他正在做项目的教授的名字,我已经有了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/

相关文章:

c# - LINQ 连接如何只选择第一条记录?

javascript - Ajax post 发送 JSON 到方法结果为 null

c# - 将数据库从本地更改为 azure 不起作用

c# - 有谁知道如何在 ParallelExtensionExtras 中使用 IOCompletionPortTaskScheduler 和 IOTaskScheduler 以及它们的用途是什么?

performance - 防止请求垃圾邮件

c# - 如果值为字符串类型则按片段搜索,但如果值为 int 则按整个搜索

c# - WPF 应用程序上的闪烁按钮

c++ - Cuda Thrust - 如何使用 sort_by_key、merge_by_key 和 reduce_by_key 优化代码

c# - 单个 "lock"或单独的读写器锁用于 IO 操作?

c# - Linq 查询中的意外结果总是 + 1