gpt4 book ai didi

c# - 将字典列表转换为模型

转载 作者:行者123 更新时间:2023-11-30 15:20:31 24 4
gpt4 key购买 nike

我有一个 List包含 Dictionary<string, string>表示来自多个连接表的数据库中的行。我尝试了各种 LINQ 方法,但我总是碰壁,因为 LINQ 不允许对此数据结构进行某些操作。我已尝试在不歪曲核心问题的情况下尽可能地简化代码示例,所以...

如何显式提取 KeyValuePairs来自DictionaryList 里面并将其放入 Model

我需要一个可扩展的解决方案,其中 Model可以对子数据做同样的事情。

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

最佳答案

匿名类型投影初始化器应该是一个简单的名称或成员访问。所以你需要添加一个明确的名称,如下所示:

data.GroupBy(x => new {S = x["dataKey"] })

关于c# - 将字典列表转换为模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40003810/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com