'Convert' Dictionary into List<object>

前端 未结 9 1897
感情败类
感情败类 2021-02-20 16:12

I have a Dictionary dictionary1 and I need to convert it into a List where Data has the properties lab

相关标签:
9条回答
  • 2021-02-20 16:30

    Just in case just helps anyone, I did it like this - will handle objects more complex than a single value type, as stated by the OP.

    // Assumes: Dictionary<string, MyObject> MyDictionary;
    List<MyObject> list = new List<MyObject>();
    list.AddRange(MyDictionary.Values.ToArray());
    
    0 讨论(0)
  • 2021-02-20 16:32

    Assuming:

    class Data
    {
        public string Label { get; set; }
    
        public int Value { get; set; }
    }
    

    Then:

    Dictionary<string, int> dic;
    List<Data> list = dic.Select(p => new Data { Label = p.Key, Value = p.Value }).ToList();
    
    0 讨论(0)
  • 2021-02-20 16:36
        public class Data
        {
            public string Key { get; set; }
    
            public int Value { get; set; }
        }
    
        private static void Main(string[] args)
        {
            Dictionary<string, int> dictionary1 = new Dictionary<string, int>();
            dictionary1.Add("key1", 1);
            dictionary1.Add("key2", 2);
    
            List<Data> data = dictionary1.Select(z => new Data { Key = z.Key, Value = z.Value }).ToList();
    
            Console.ReadLine();
        }
    
    0 讨论(0)
  • 2021-02-20 16:40
    myDictionary.Select(x => new Data(){ label = x.Key, value = x.Value).ToList();
    
    0 讨论(0)
  • 2021-02-20 16:43

    Try

    dictionary1.Select(p => new Data(p.Key, p.Value)).ToList();
    
    0 讨论(0)
  • 2021-02-20 16:46

    Perhaps you could use LINQ?

    dictionary1.Select(p => new Data(p.Key, p.Value)).ToList()
    

    This is however using yield and thus loops in the background...

    0 讨论(0)
提交回复
热议问题