2010-10-27 46 views
3

所以我一直在尋找一個簡單的例子來希望解決一個簡單的問題。帶有數據對象的動態LINQ

我有一個簡單的對象ListTest的名單(名單)

public class ListTest{ 
{ 
    public string perName { get; set; } 
    public string perSex { get; set; } 
    public ListTest(string pName, string pSex) 
    { 
     this.perSex = pSex; 
     this.perName = pName; 
    } 
} 

我有一些數據加載它:

 List<ListTest> tryIt = new List<ListTest>(); 
     tryIt.Add(new ListTest("Karen", "F")); 
     tryIt.Add(new ListTest("Kate", "F")); 
     tryIt.Add(new ListTest("Glen", "M")); 
     tryIt.Add(new ListTest("Tiger", "M")); 
     tryIt.Add(new ListTest("Clementine", "F")); 
     tryIt.Add(new ListTest("Magnolia", "F")); 

現在我想用一個Lambda表達式進行查詢:

 var things = tryIt 
        .Where(sex => (sex.perSex == "F")) 
        .OrderBy(sex => sex.perName); 

但我想動態地做到這一點,以防萬一我想改變我的位置「perName」。

我能夠爲您的表達式創建Lambda表達式,但我無法弄清楚如何將其穿過目標行並將其分配給where子句並執行它。

 IQueryable<ListTest> iq = tryIt.AsQueryable(); 
     ParameterExpression pe = Expression.Parameter(typeof(ListTest), "Person"); 
     Expression paEx = Expression.Property(pe, "perSex"); 
     Expression right = Expression.Constant("F"); 
     Expression eqEx = Expression.Equal(paEx, right); 
     Expression lE = Expression.Lambda<Func<ListTest, bool>>(eqEx, pe); 

這應該是一個簡單的4或5行的解決方案,但我不能找到一個容易辨認溶液的例子。

我應該在這些行中使用MethodCallExpression還是其他東西?

感謝,

回答

1

你可以嘗試這樣的事情:

IEnumerable<ListTest> things = tryIt; 

if (someBooleanLogic) 
    things = things.Where(l => l.perSex == "F"); 
else 
    things = things.Where(l => l.perName == "Tiger"); 

things = things.OrderBy(sex => sex.perName); 

List<ListTest> filteredAndSorted = things.ToList(); 

編輯:

或者,另外還有流行LINQ Dynamic Query Library,在那裏你可以表格幾乎無論你想要(當然是動態的)。

+0

試圖使用MethodCallExpression爲了保持查詢動態。我希望將參數表達式改爲對象的不同屬性。例如讓查詢返回按perName排序的集合。 – 2010-10-28 00:45:30

+0

好的。我不*完全*確定我明白你的目標是什麼,但我已經爲我的答案添加了另一個資源 - LINQ動態查詢庫。你可能已經意識到了這一點,但如果沒有,它可能對你有用 - 它非常強大。 – shaunmartin 2010-10-28 01:09:54

+0

LINQ動態查詢庫是要走的路... – codekaizen 2010-10-28 01:18:40

0

我發現這個post最優雅的解決方案。它允許我構建一個非常靈活和清晰的解決方案,而不會陷入參數地獄。