I have a Dictionary
and I need to convert it into a List
where Data
has the properties lab
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());
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();
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();
}
myDictionary.Select(x => new Data(){ label = x.Key, value = x.Value).ToList();
Try
dictionary1.Select(p => new Data(p.Key, p.Value)).ToList();
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...