mongodb c# select specific field dot notation

↘锁芯ラ 提交于 2019-12-13 00:44:03

问题


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:

  1. Field can be of any type
  2. Return type is T
  3. Field can be inside a sub field
  4. 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

  1. Which element is array in this chain?
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!