代码之家  ›  专栏  ›  技术社区  ›  Eli Korvigo

从Ilist获取IDictionary

c#
  •  3
  • Eli Korvigo  · 技术社区  · 14 年前

    如何从IList获得IDictionnay

    2 回复  |  直到 14 年前
        1
  •  5
  •   Steve Willcock    14 年前

    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; }
        }
    }
    

    IDictionary<string, int> dictionary2 = list.ToDictionary(x => x.Name, x => x.Age);
    
        2
  •  4
  •   qJake    14 年前

    列表有一个组件,字典有两个组件。你不能简单地转换它们。

    如果你想让你的字典 <int, object> ,在哪里 int

    Dictionary<int, object> dict = new Dictionary<int, object>();
    myList.ForEach(i => dict.Add(myList.IndexOf(i), i)); // Linq magic!
    

    object 使用列表类型,并确保 using System.Linq; .


    或使用 ToDictionary()