C# List<object> to Dictionary<key, <object>>
One most straight forward way would be to use the int key
as key
like this:
List<Person> List1 = new List<Person>();
int key = 0; //define this for giving new key everytime
var toDict = List1.Select(p => new { id = key++, person = p })
.ToDictionary(x => x.id, x => x.person);
The key is the lambda expression:
p => new { id = key++, person = p }
Where you create an anonymous object
having id
and person
properties. The id
is incremental key
while the person
is simply the element of your List<Person>
If you need to use the Person
's Id instead, simply use:
List<Person> List1 = new List<Person>();
var toDict = List1.Select(p => new { id = p.Id, person = p })
.ToDictionary(x => x.id, x => x.person);
This should work for your case:
int key = 0; // Set your initial key value here.
var dictionary = persons.ToDictionary(p => key++);
Where persons
is List<Person>
.
You were almost there, just change variable type from List<string>
to List<Person>
and you are good to go. You can use your LINQ query as is, example:
List<Person> persons = new List<Person>();
var p1 = new Person();
p1.Name = "John";
persons.Add(p1);
var p2 = new Person();
p2.Name = "Mary";
persons.Add(p2);
var toDict = persons.Select((s, i) => new { s, i })
.ToDictionary(x => x.i, x => x.s);
However, while I don't have anything against LINQ, in this particular case a much more readable approach is using a regular loop like this:
var result = new Dictionary<int, Person>();
for (int i = 0; i < persons.Count; i++)
{
result.Add(i, persons[i]);
}
Jon Skeet suggests yet another way of doing it, using Enumerable.Range
, which I tested and it works perfectly:
var toDict = Enumerable.Range(0, persons.Count)
.ToDictionary(x => x, x => persons[x]);