我一般使用List<T>
进行收藏。 但是,如果我需要对集合进行快速查找,那么例如在下面的例子中我会用一个字典,所以我可以很快看它由id
:字典<TKey,TValue>比列表上的LINQ更快<T>?
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);
}
}
}
我发现这很有趣:http://www.dotnetperls.com/hybriddictionary(有趣的是,注意到混合词典只有*很少* 5项更快 - 当然,使用特定的设置描述) – 2011-02-27 06:49:24