How do I reference a field in Linq based on a dynamic fieldname

后端 未结 5 1327
予麋鹿
予麋鹿 2021-01-05 08:22

Firstly, apologies for the bad question title - not entirely sure if I am asking the correct thing.

Normally I can do the following to access a field:



        
相关标签:
5条回答
  • 2021-01-05 08:36

    It is definitely doable but does get alot more complicated. If you want to do a completely dynamic LINQ query you should check out these posts by Scott Hanselman.

    • The Weekly Code Sample 48 - DynamicQueryable makes custom LINQ expressions easier
    • The Weekly Code Sample 47 - ASP.NET 3.5 Dynamic Data: FilterRepeaters and Dynamic Linq Query Generation
    0 讨论(0)
  • 2021-01-05 08:40

    You need to use reflection, like this: (Untested)

    somevalue = typeof(MyTable).GetProperty(fieldName).GetValue(table, null);
    
    0 讨论(0)
  • 2021-01-05 08:43

    Weirdly I have just been reading something similar on Scott Hanselman's blog, this is to set the where or ordering by a field name in a string but I think the select could be done in the same way. See:

    http://www.hanselman.com/blog/TheWeeklySourceCode48DynamicQueryableMakesCustomLINQExpressionsEasier.aspx

    The core being something like :

    Dim Northwind As new NorthwindDataContext
    Dim query = Northwind.Products
            .Where("CategoryID=2 And UnitPrice>3")
            .OrderBy("SupplierID")
    GridView1.DataSource = query
    GridView1.DataBind()
    

    It may require some dynamic data references.

    0 讨论(0)
  • 2021-01-05 08:43

    In order to do this, you will need to use reflection.

    public object GetField(object obj, string fieldName) { 
      var t = obj.GetType();
      var field = t.GetField(fieldName);
      return field.GetValue(obj);
    }
    
    somevalue = GetField(table, "someFieldName");
    

    This works as long as the field is both instance and public. You'd need to modify the GetField method call slightly if the accessibility was less than public.

    0 讨论(0)
  • 2021-01-05 09:02

    If you have string s = "sampleField";, then you can just use reflection:

    object value = table.GetType().GetProperty(s).GetValue(table, null);
    

    If you need the PKID as a string, it is more complex, and you need to use a runtime-generated lambda. Exactly how depends slightly on the implementation - for example, to identify the PK from LINQ-to-SQL, see this answer which looks at the data-contexts metadata.

    0 讨论(0)
提交回复
热议问题