LINQ to Entities - Addressing class properties with their string names

前端 未结 3 1248
小蘑菇
小蘑菇 2021-01-16 20:12

I have a Kendo grid that has serverside filtering turned on. The field to filter by is passed as a string. For example, I want to filter by \"SampleId\". Now, I need to writ

3条回答
  •  天命终不由人
    2021-01-16 20:56

    I didn't think any of these answered actually how to do the getproperty so included my working code after further research. mymodelclass is the class of the entity/model used to MyFilteredData.

            var srchItem1 = typeof(mymodelclass).GetProperty("Name");
            var srchItem2 = typeof(mymodelclass).GetProperty("Description");
            var srchItem3 = typeof(mymodelclass).GetProperty("LongDescription");
            if (MySearchText != null && srchItem1 != null)
                {
                    if (srchItem2 == null) { srchItem2 = srchItem1; }
                    if (srchItem3 == null) { srchItem3 = srchItem1; }
                    MyFilteredData = MyFilteredData.
                            Where(c => srchItem1.GetValue(c).ToString().ToLower().Contains(MySearchText.ToLower()) ||
                            srchItem2.GetValue(c).ToString().ToLower().Contains(MySearchText.ToLower()) ||
                            srchItem3.GetValue(c).ToString().ToLower().Contains(MySearchText.ToLower())
                    );
                }
    

提交回复
热议问题