c# - Dictionary<TKey, TValue> 是否比 List<T> 上的 LINQ 更快?

标签 c# list collections dictionary

我一般用List<T>用于收藏。 但是如果我需要快速查找一个集合,那么例如在下面的示例中,我将使用字典,以便我可以通过 id 快速查找它:

Dictionary<int, Customer>

但是因为我可以使用 LINQ 来查询 List<T>无论如何,如下所示,是否有任何理由去解决使用字典而不是列表的麻烦?是字典更快还是 LINQ 在幕后做了一些使其同样快的事情?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Customer> customers = new List<Customer>()
            {
             new Customer { Id = 234, FirstName = "Jim", LastName = "Smith" },
             new Customer { Id = 345, FirstName = "John", LastName = "Thomas" },
             new Customer { Id = 654, FirstName = "Rick", LastName = "Ashton" },
             new Customer { Id = 948, FirstName = "Rod", LastName = "Anders" }
            };

            var customer = (from c in customers
                           where c.Id == 654 select c).SingleOrDefault();
            Console.WriteLine(customer.Display());

            Console.ReadLine();

        }
    }


    public class Customer
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

        internal string Display()
        {
            return String.Format("{0}, {1} ({2})", LastName, FirstName, Id);
        }

    }
}

最佳答案

如果您逻辑上想要创建一个集合,您可以在其中轻松地通过他们的 ID 查找客户,我会使用某种形式的 IDictionary<int, Customer> .这表达了您想要实现的目标。

现在您可以使用列表来做同样的事情,正如 leppie 所说,对于小型数据集,它的速度差不多甚至更快——但对于小型数据集,它无论如何都会非常快,那你为什么要关心?我认为更重要的是告诉代码的读者您要对集合做什么 - 字典比列表更有效地实现了这个目标,IMO。

关于c# - Dictionary<TKey, TValue> 是否比 List<T> 上的 LINQ 更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3448194/

相关文章:

java - 链表中的节点(int索引)

c# - 免费的 MS Word 库

c# - 第一个没有断言/预期异常的 TDD 测试。这值得么?

c# - 列表的所有排列

c++ - 遍历对列表的 vector

c# - 可以使用 int 作为 KeyedCollection 中的键吗

c# - 为什么新线程可以访问UI?

Python 列表操作和列表比较

Python 比较两个键/值对

wpf - 如何将 List 作为 ItemSource 绑定(bind)到 XAML 中的 ListView?