tags:

views:

138

answers:

2

Hi Guys. I have a linq question (linq to sql). I have the following peice of code which works fine;

       var queryx = (from sa in d1.SampleAttributes
                      where nodeTable.ToList().Distinct().Contains(sa.client_post_code_prefix)
                     select sa.SampleId).Distinct();

Note: nodeTable is of type IQueryable

However, I would like to change this so that the column name within the contain method can be decided at runtime. I determine the column name from another query dependent on certain user filters being applied and would ideally like something with the follwing logic;

//please note that the string I pass into obtain a 'column object' always shares the same name as the column

        var columnWhatever = GetColumnName(string colName);

        var queryx = (from sa in d1.SampleAttributes
                      where nodeTable.ToList().Distinct().Contains(sa.client_post_code_prefix)
                     select sa.SampleId).Distinct();

So far I have been unable to find anything that will allow this and I'm beggining to think that Linq does not allow such logic. Any help would be much appreciated

+3  A: 

You might take a look at the Dynamic LINQ library. I posted about it here. Take a look and see if that might help you. Also see Scott Guthrie's post about it here.

Brian Sullivan
By far the worst of both worlds: dynamic sql and linq. great.
Chris Lively
+1  A: 

If this is LINQ to object you can do this very easily using reflection. To wit:

string colName;
var queryx = (from sa in d1.SampleAttributes
              where nodeTable.Contains(
                                 sa.GetType()
                                   .GetProperty(colName)
                                   .GetValue(sa, null)
                                   .ToString()
                             )
              select sa.SampleId).Distinct();

This is assuming that nodeTable is an IEnumerable<string>.

It would be better to only perform the reflection piece once. Say that the compile-time type of sa is SampleAttribute. Then you could do the following:

string colName;
PropertyInfo info = typeof(SampleAttribute).GetProperty(colName);
Func<SampleAttribute, string> func = sa => info.GetValue(sa, null).ToString();
var queryx = (from sa in d1.SampleAttributes
              where nodeTable.Contains(func(sa))
              select sa.SampleId).Distinct();

If this is LINQ to SQL you can do this easily using System.Linq.Expressions.Expression. If you give a little more detail about the type of nodeTable I can walk you through this.

Jason
Hi Jason this is linq to sql. I'm assuming your answer would not apply to linq to sql although on first sight I can't understand why it would work on linq to object and not on linq to sql.
saj
And nodeTable is of type IQueryable<string>. Thanks
saj
Anyone got any ideas?
saj