3

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
Chris Hayes
  • 3,666
  • 5
  • 35
  • 70
  • FYI, even if it's static, `Distinct()` does not take a parameter (unless you can use morelinq). – Bala R Jun 13 '11 at 20:16
  • Actually, as of .NET 3.5, `Distinct()` [*can* take a parameter](http://msdn.microsoft.com/en-us/library/bb338049.aspx): an `IEqualityComparer` that can be used to control how the method determines distinctness. – Dan J Jun 13 '11 at 20:23
  • Related if not duplicated http://stackoverflow.com/q/41244/340760 – BrunoLM Jun 13 '11 at 20:33
  • isn't there some simple way to do this with reflection? – Chris Hayes Jun 13 '11 at 20:48

3 Answers3

1

You can try this

(p => p.GetType().GetProperty(exp).GetValue(p, null)).ToString();
Sergey Glotov
  • 19,479
  • 11
  • 78
  • 93
Gowtham
  • 11
  • 1
1

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 :)

cecilphillip
  • 10,551
  • 3
  • 33
  • 38
1

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);
        }
    }
rerun
  • 23,827
  • 6
  • 44
  • 74