'将'Dictionary <string,int>转换为List <object>

Jen*_*nha 9 .net c# linq

我有一个Dictionary<string,int> dictionary1,我需要将其转换为具有properties = dictionary1.key和= dictionary1.value 的List<Data>where .我不想使用for/foreach循环(由我自己编写),因为为了避免它我试图使用Dictionary.Datalablevalue

另一个选择是有两个不同的词典(dictionary2和dictionary3)where dictionary2<string,keyOfDictionary1>dictionary3<string,valueOfDictionary1>.

我有道理吗?那可能吗?有更好的选择吗?

aba*_*hev 16

假设:

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

    public int Value { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后:

Dictionary<string, int> dic;
List<Data> list = dic.Select(p => new Data { Label = p.Key, Value = p.Value }).ToList();
Run Code Online (Sandbox Code Playgroud)


Leo*_*ard 5

也许你可以使用LINQ?

dictionary1.Select(p => new Data(p.Key, p.Value)).ToList()
Run Code Online (Sandbox Code Playgroud)

然而yield,这是使用,因此在后台循环...

  • 这将要求`Data`有一个构造函数,它将值作为参数,这在问题中没有指定. (3认同)