gpt4 book ai didi

c# - 使用 LINQ 将属性值与字典键匹配

转载 作者:行者123 更新时间:2023-11-30 22:53:07 24 4
gpt4 key购买 nike

假设我有这两个简单的类:

public class MyObject
{
public string name;
public string objectProperty;
[other properties]
}

public class Referencer
{
public string name;
public Dictionary<string, object> objectDictionary;
}

和 MyObject 实例列表:

List<MyObject> myObjects = new List<MyObject>
{
new MyObject(name: "name1", objectProperty: "objectProperty1", other properties...),
new MyObject(name: "name2", objectProperty: "objectProperty2", other properties...),
new MyObject(name: "name3", objectProperty: "objectProperty3", other properties...),
other myObjects...
}

还有这样的字典:

Dictionary<string, Dictionary<string, object>> sampleDictionary = new Dictionary<string, Dictionary<string, object>>
{
{"name3", new Dictionary<string, object> { {"property1", "value1"}, {"property2", "value2"} } },
{"name2", new Dictionary<string, object> { {"property3", "value3"}, {"property4", "value4"} } },
{"name1", new Dictionary<string, object> { {"property5", "value5"}, {"property6", "value6"} } },
other entries...
};

我需要能够创建一个 List<Referencer>匹配myObjectssampleDictionary根据规则:

myObjects.name == sampleDictionary.Key

我试过使用 LINQ ForEach , Where , ToDictionary ,但我想我这里缺少一些东西,需要你的帮助。

最佳答案

稍微扩充@AleksAndreev 的答案:

myObjects
.Where(x => sampleDictionary.ContainsKey(x))
.Select(x => new Referencer { name = x.name, objectDictionary = sampleDictionary[x.name] });

关于c# - 使用 LINQ 将属性值与字典键匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57610152/

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