Is Dictionary<TKey, TValue> faster than LINQ on a List<T>?

Viewed 11014

I generally use List<T> for collections. But if I need a fast lookup on a collection, then e.g. in the following example I would use a Dictionary so I could look it up quickly by id:

Dictionary<int, Customer>

But since I can use LINQ to query the List<T> anyway, as below, is there any reason to go through the trouble of using a Dictionary instead of a List? Is Dictionary faster or is LINQ doing something behind the scenes that makes it just as fast?

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);
        }

    }
}
6 Answers
Related