为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
慕森王 2023-09-16 15:56:53
假设我有这两个简单的类: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>匹配:myObjectssampleDictionarymyObjects.name == sampleDictionary.Key我尝试过使用 LINQ ForEach, Where, ToDictionary,但我认为我这里缺少一些东西,需要你的帮助。
查看完整描述

1 回答

?
偶然的你

TA贡献1841条经验 获得超3个赞

稍微扩充一下:

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



查看完整回答
反对 回复 2023-09-16
  • 1 回答
  • 0 关注
  • 67 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信