简体   繁体   中英

How do you call linq fields dynamically

if I'm passing in a string column name, how do I call a distinct list of items by property name?

private myEntities db = new myEntities();

...
//function passes in string
var vals = db.myEntityClass
                .Select(v => v.????).Distinct() //I want this to be selected dynamically

You can try this

(p => p.GetType().GetProperty(exp).GetValue(p, null)).ToString();

If you are using .NET 4.0, here's a post by David Fowler that makes use of the new dynamic type feature to create a DynamicQueryable and DynamicExpressionBuilder which allows you to reference entity properties dynamically.

Or.. if you rather get straight to it, he's also created a library http://bitbucket.org/dfowler/dynamiclinq the encapsulates the functionality. It's also on NuGet:)

One thing you can do is use an extension method to get the property I wrote a quick example but you will need to add additional sanity checks for your data but this is the base case.

 static class BadIdea
    {
        public static Typ GetValue<Typ>(this object o, string PropName)
        {

            Type T = o.GetType();
            Typ ret = default(Typ);
            System.Reflection.PropertyInfo pi = T.GetProperty(PropName);
            if (pi != null)
            {
                object tempRet = pi.GetValue(o, new object[] { });
                ret = (Typ)Convert.ChangeType(tempRet, ret.GetType());
            }
            else
            {
                return default(Typ);
            }
            return ret;
        }


        public class Tst
    {
        public int A { get; set; }
        public int B { get; set; }
    }

    static void Main(string[] args)
    {
        List<Tst> vals =new List<Tst>() { new Tst() { A = 4, B = 6 }, new Tst() { A = 4, B = 7 } };
        var lst = vals.Where((x) => x.GetValue<int>("A") == 4);
        foreach (Tst ot in lst)
        {
            Console.WriteLine("A : {0} ; B: {1}", ot.A, ot.B);
        }
    }

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