问题
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.
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.
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
.
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);
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.
Here's the relative parts of the class:
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");
}
}
}
I'd like to use LINQ if possible, but not a huge deal if not.
回答1:
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.
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);
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);
来源:https://stackoverflow.com/questions/43805309/find-object-in-list-with-given-property-value-then-find-dictionary-value