开发者

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();

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


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);
        }
    }


You can try this

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜