scapegoat17
scapegoat17

Reputation: 5821

Dynamic distinct values using Linq to SQL

I was unsure if what I wrote as a Title would suffice, but I will do my best to explain what I am trying to accomplish here:

I am trying to recreate this query that I use to look up distinct data from TestColumn:

 List<string> groupQuery = (from p in testDepo
                                      group p by new { p.TestColumn}
                                      into distinctTest
                                      select distinctTest.First().TestColumn).ToList();

But instead of statically call TestColumn. I would like to dynamically pass in the name: TestColumn into a variable and then do my distinct value query using the variable name.

So far I have this:

string primaryColumn = "TestColumn"
List<string> groupQuery= (from p in testDepo
                                    group p by new { primaryColumn }
                                    into distinctTest
                                    select distinctTest.First().GetType().GetProperty(primaryColumn).GetValue(distinctTest.First()).ToString()).ToList();

I know i am probably doing something silly, but i cant quite wrap my head around it right now. my dynamic query only half works. It is only getting the first distict value, but not the rest of them. Can anyone help me out?

Upvotes: 2

Views: 1039

Answers (2)

david.s
david.s

Reputation: 11403

You can create a Func from an Expression using your property column string like this:

var primaryColumn = "TestColumn";
var param = Expression.Parameter(typeof(Test), "p");
var col = Expression.Property(param, primaryColumn);
var lambda = Expression.Lambda(col, param);
var func = lambda.Compile();

Then use it in your query like this:

List<string> groupQuery= (from p in testDepo
                          group p by func.DynamicInvoke(p)
                          into distinctTest
                          select distinctTest.First()
                                             .GetType()
                                             .GetProperty(primaryColumn)
                                             .GetValue(distinctTest.First())
                                             .ToString()
                          ).ToList()

Upvotes: 4

jdweng
jdweng

Reputation: 34421

What is TestDepro? You need to be able to return the column by name something like p[primaryColumn].

Upvotes: 0

Related Questions