Reputation: 423
How to get a IDictionnay form a IList
Upvotes: 3
Views: 805
Reputation: 26849
You can use Linq to easily get a Dictionary from a List by using the ToDictionary extension method and supplying an expression to get the key - e.g.
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 Jon pointed out, if you need to use a different value for the 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);
Upvotes: 5
Reputation: 17139
A List has one component to it, and a Dictionary has two components. You can't simply convert them.
If you want your Dictionary to be <int, object>
, where int
is the index of the information in your List...
Dictionary<int, object> dict = new Dictionary<int, object>();
myList.ForEach(i => dict.Add(myList.IndexOf(i), i)); // Linq magic!
Replace object
with your List type, and make sure you are using System.Linq;
.
Or use ToDictionary()
.
Upvotes: 4