2010-01-27 18 views
3

我有一個linq問題(linq to sql)。我有以下代碼工作正常;Linq查詢問題 - 在運行時確定列

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

注:nodeTable的類型是IQueryable的

不過,我想改變這種做法,在含有方法中列名可以在運行時決定的。我從另一個查詢中確定列名,這個查詢依賴於正在應用的特定用戶過濾器,並且理想情況下會使用下面的邏輯來處理某些事情;

//請注意,我傳遞到字符串獲得「列對象總是共享相同的名稱列

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

到目前爲止,我一直無法找到任何東西,讓這個和我開始認爲Linq不允許這樣的邏輯。任何幫助將不勝感激

+0

dup? http://stackoverflow.com/questions/2148309/how-do-i-reference-a-field-in-linq-based-on-a-dynamic-fieldname – 2010-01-27 16:23:10

+0

@Rob - 不一定;第一個可以用反射來回答,但這可能是其他的東西... – 2010-01-27 16:24:00

+1

@saj - 這裏的底層LINQ實現是什麼? LINQ到對象?實體框架? LINQ到SQL?不幸的是,這很重要。 – 2010-01-27 16:24:29

回答

3

你可能會看看動態LINQ庫。我發佈了關於它here。看一看,看看是否可以幫助你。另請參閱Scott Guthrie的文章here

+0

迄今爲止最糟糕的兩個世界:動態SQL和LINQ。大。 – NotMe 2010-01-27 16:30:37

2

如果這是LINQ的對象,你可以很容易地使用反射來做到這一點。即:

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

這是假設nodeTableIEnumerable<string>

只做一次反射片會更好。假定編譯時間類型saSampleAttribute。然後,你可以做到以下幾點:

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

如果是這樣的LINQ to SQL,你可以做到這一點很容易地使用System.Linq.Expressions.Expression。如果你提供更多關於nodeTable類型的細節,我可以引導你完成這個任務。

+0

嗨賈森這是LINQ到SQL。我假設你的答案不會適用於LINQ到SQL,雖然一見鍾情,我不明白爲什麼它會在LINQ上工作,而不是在LINQ上的SQL。 – saj 2010-01-27 20:47:39

+0

和nodeTable是IQueryable類型。謝謝 – saj 2010-01-27 20:59:54