You can use Linq to easily retrieve a Dictionary from a list using the ToDictionary extension method and provide an expression to get the key - for example,
internal class Program
{
private static void Main(string[] args)
{
IList<Person> list = new List<Person> {new Person("Bob", 40), new Person("Jill", 35)};
IDictionary<string, Person> dictionary = list.ToDictionary(x => x.Name);
}
}
public class Person
{
private readonly int _age;
private readonly string _name;
public Person(string name, int age)
{
_name = name;
_age = age;
}
public int Age
{
get { return _age; }
}
public string Name
{
get { return _name; }
}
}
Alternatively, as John pointed out, if you need to use a different value for dictionary entries, you can also specify a second expression to get the value — as follows:
IDictionary<string, int> dictionary2 = list.ToDictionary(x => x.Name, x => x.Age);
source
share