I am a beginner c# developer and I need to create a dictionary of object from my list. First, let me define my object as Person.
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
Now I have a list of my person object. List<Person>
How to query it in LinQ to convert it to a Dictionary of Person from my list? My desired output is:
Dictionary<key, <Person>>
Where key is an incrementing integer per Person object.. Any help is appreciated. Thank you.
I found this code online but it works with List<string>
List<string> List1
var toDict = List1.Select((s, i) => new { s, i })
.ToDictionary(x => x.i, x => x.s)
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>
.
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);
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]);
This is my solution:
var key = 0;
IDictionary<int, Person> personDictionary = personList
.Select(x => new KeyValuePair<int,Person>(key++, x))
.ToDictionary(y => y.Key, y => y.Value);
where personList
is List<Person>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.