简体   繁体   中英

Get value of a column which name is generated at runtime in Linq?

I have this query:

(from mt in edmxObject.MyTable 
 where mt.Field1 != null 
 select mt.Field6)
.Distinct()
.ToList())

There are also field Field2, Field3, Filed4 and Field5 which a same in nature. They hold an integer number, but they can also be nullable.

I want to get whether some of the fields Field1, Field2, ..., Field5 has a value or they have a null value.

If I know the name of the column as a string like "FieldX" which is in the set (Field1, Field2, ..., Field5) how can I get a Linq query at runtime with the appropriate column and then execute it on my edmx model to get the value of the given field?

I have updated the sentence, basically added in the where clausule what I used in the select. I'm using reflection to get access to the properties and values.

        string fiealdName = "Field1";
        var neL = l.Where(f => f.GetType()
                                .GetProperty(fiealdName).GetValue(f, null) != null)
                   .Select(f => f.GetType()
                   .GetProperty(fiealdName).GetValue(f, null)
                   .GetValue(f, null))
                   .Distinct()
                   .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM