在列表中查找具有给定属性值的对象,然后查找字典值 [英] Find object in list with given property value then find dictionary value
问题描述
我有一个对象列表.这些对象中的每个对象都有一个 Name
属性,一个 ObservablePairCollection
只是一个自定义词典,与字典完全一样,具有键/值对.
I have a list of objects. Each of these objects has a Name
property, and an ObservablePairCollection
which is just a custom dictionary that works EXACTLY like a dictionary, has a key/value pair.
给出两个字符串,一个用于名称,一个用于键,我想找到首先与给定名称匹配的对象,然后从该模型的字典中选择与给定键值匹配的 pair
Given two strings, one for name and one for key, I want to find the object that first matches the name given, and then selects the pair
from that model's dictionary that matches the given key value.
示例:给定名称的字符串"model1"和键的"Latitude",应找到名称属性等于 model1
的对象,然后在该对象的字符串/值对中找到键等于 Latitude
的地方应返回字典.
Example: Given the string "model1" for name, and "Latitude" for the key, an object who's name property equals model1
should be found, and then a key/value pair in the object's dictionary should be returned where the key equals Latitude
.
当前,我可以使用以下方法来完成第一部分以匹配 Name
:
Currently I can do the first part to match the Name
by using:
private ObservableCollection<ModelBase> models;
//add objects to models
string stringToFind = "model1";
models.Single(m => m.Name == stringToFind);
因此,这将返回其 Name
属性等于 model1
的对象.
So, this returns the object who's Name
property equals model1
.
尽管如此,我还是找不到用于获取键/值对的正确语句.
I'm unable to find the right statement to use to get the key/value pair though.
这是课程的相关部分:
private ObservablePairCollection<string, string> _fields = new ObservablePairCollection<string, string>();
public ObservablePairCollection<string, string> Fields
{
get { return _fields; }
set { _fields = value; OnPropertyChanged("Fields"); }
}
private string _name;
public string Name
{
get { return _name; }
protected set
{
if (_name != value)
{
_name = value;
OnPropertyChanged("Name");
}
}
}
如果可能的话,我想使用LINQ,否则请不要多用.
I'd like to use LINQ if possible, but not a huge deal if not.
推荐答案
首先,为什么要 Single
?必须只有一个具有给定 Name
的对象,您是否必须在此特定代码中强制?请记住,Single
开销很大,因为它会枚举整个集合以确保找到的对象是唯一的.
First of all, why Single
? Must there be only one object with the given Name
and must you enforce it in this specific code? Bear in mind that Single
is expensive because it will enumerate the whole collection to make sure the found object is unique.
如果您只想查找第一个(如果有),则只需使用恰当命名的 First
扩展方法:
If you are just interested in finding the first, if any, then simply use the aptly named First
extension method:
models.First(m => m.Name == stringToFind);
好,因此返回具有给定 Name
的第一个对象(如果有的话),只需要过滤 Fields
属性:
Ok, so that returns the first object with a given Name
, if any, you simply need to filter the Fields
proyerty:
var pair = models.First(m => m.Name == stringToFind)
?.Fields
.First(f => f.Key = keyToFind);
这篇关于在列表中查找具有给定属性值的对象,然后查找字典值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!