【发布时间】:2011-03-27 18:23:17
【问题描述】:
我通常使用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);
}
}
}
【问题讨论】:
-
我发现这很有趣:dotnetperls.com/hybriddictionary(有趣的是,混合字典仅对 很少 ~5 个项目更快——当然,使用那个特定的设置描述)
标签: c# list collections dictionary