Get Idictionnary from Ilist

How to get IDictionnay form for IList

+3
source share
2 answers

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);
+5
source

A list has one component, and a dictionary has two components. You cannot just convert them.

If you want your dictionary to <int, object>be where intis 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!

object List , using System.Linq;.


ToDictionary().

+4

Source: https://habr.com/ru/post/1753837/


All Articles