将字典列表转换为模型 [英] Converting a list of dictionaries to models
问题描述
我有一个List
,其中包含一个Dictionary<string, string>
,该Dictionary<string, string>
表示来自多个联接表的数据库中的行.我已经尝试过各种LINQ方法,但是我总是碰壁,LINQ只是不允许对该数据结构进行某些操作.我已经尽我所能简化了代码示例,而又没有错误地表达了核心问题.
I have a List
containing a Dictionary<string, string>
that represents lines from a database from multiple joined tables. I have tried all sorts of LINQ approaches but I always hit a wall where LINQ just doesn't allow certain operations on this data structure. I have tried to simplify the code example as much as I think I can without misrepresenting the core issue so...
如何从List
内部的Dictionary
中提取显式的KeyValuePairs
并将其放入Model
中?
How can I extract explicit KeyValuePairs
from a Dictionary
inside of a List
and put it into a Model
?
我需要一个可伸缩的解决方案,其中Model
可以对subData做同样的事情.
I need a scale-able solution where the Model
could do the same with the subData.
public class Program
{
public static void Main(string[] args)
{
List<Dictionary<string, string>> data = GetData();
data.Add(new Dictionary<string, string>() { ["modelData"] = "Bob", ["subModelData"] = "Frank" });
data.Add(new Dictionary<string, string>() { ["modelData"] = "Nancy", ["subModelData"] = "Boy" });
List<Model> models = new List<Model>();
//Fails in this linq statement. Anonymous types don't allow key accessors
foreach (Dictionary<string, string> distinctModel in data.GroupBy(x => new { x["dataKey"] }))
{
List<Dictionary<string, string>> newModelData = data.Where(d => d["data1Key"] == distinctModel["dataKey"]).ToList();
Model newModel = new Model(newModelData);
models.Add(newModel);
}
}
}
public class Model
{
public string modelData;
public List<Dictionary<string, string>> subData;
public Model(List<Dictionary<string, string>> data) {
modelData = data[0]["dataKey"];
data.Remove("dataKey");
subData = data;
}
}
推荐答案
匿名类型投影初始值设定项应为简单名称或成员访问权限.因此,您需要添加一个明确的名称,如下所示:
Anonymous type projection initializer should be a simple name or member access. So you need to add an explicit name like below:
data.GroupBy(x => new {S = x["dataKey"] })
这篇关于将字典列表转换为模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!