问题
In addition for my previous question: mongodb c# select specific field.
I'm writing a generic method for selecting a specific field.
the requirements are:
- Field can be of any type
- Return type is T
- Field can be inside a sub field
- Field can be inside array items - in that case its OK to select the specific field of all the items in the array
for shorts, im looking for the "select" / dot notation capability. for example:
the wanted method:
T GetFieldValue<T>(string id, string fieldName)
the document:
persons
{
"id": "avi"
"Freinds" : [
{
"Name" : "joni",
"age" : "33"
},
{
"Name" : "daniel",
"age" : "27"
}]
}
The goal is to call the method like this:
string[] myFriends = GetFieldValue<string[]>("avi", "Freinds.Name");
myFriends == ["joni","daniel"]
as far as i know, using projection expression with lambda is no good for items in array, I was thinking more dot notation way.
note: I'm using the new c# driver (2.0)
Thanks A lot.
回答1:
I don't see good approach with don notation in string, because it has more issues with collections than generic approach:
For example Persion.Friends.Name
- Which element is array in this chain?
- You should apply explicit conversion for collection elements (possible place of bugs)
Generic methods are more reliable in support and using:
var friends = await GetFieldValue<Person, Friend[]>("avi", x => x.Friends);
var names = friends.Select(x=>x.Name).ToArray();
来源:https://stackoverflow.com/questions/31161104/mongodb-c-sharp-select-specific-field-dot-notation