【问题标题】:Performance comparison of Creating a List of Objects vs Creating a Dictionary using Linq?创建对象列表与使用 Linq 创建字典的性能比较?
【发布时间】:2014-02-21 21:46:51
【问题描述】:

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

假设:一位教授下可以有多个学生,但每个 学生只分配了教授。

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

    List<int> profIds= students.Select(s => s.profId).Distinct();
    
  2. 然后我尝试更新他正在做项目的教授的名字,我已经有 profesors 类型的 IEntityRepository&lt;Professor&gt; 对象。这一步我有两种替代方法。

第一:

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


【解决方案1】:

在我看来,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()
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多