2012-09-27 123 views
0

我相信這是菜鳥的錯誤,但我自己找不到答案。LINQ「where」帶參數

public class Database : DataContext 
{ 
    public Table<Record> RecordTable; 
    public Database(string connection) : base(connection) {} 
} 

[Table(Name = "RecordsTable")] 
public class Record 
{ 
    [Column(IsPrimaryKey = true, CanBeNull = false)] 
    public int codedID; 
} 

// inside some class 
private void ReadTestData(Database openedDatabase, int expectedValue) 
{ 
    Table<Record> rec = openedDatabase.GetTable<Record>(); 
    var q = 
     from a in rec 
     where (GetMonth == expectedValue) // <--- that line doesn't work 
     select a; 

    foreach (var b in q) { System.Console.WriteLine("something"); } 
} 

static Expression<Func<Record, int>> GetMonth = a => a.codedID/10000; 

public static int DecodeMonth(int codedID) 
{ 
    int month = codedID/10000; 
    //(...) 
    return month; 
} 

我想打電話DecodeMonth功能和比較它與expectedValue返回值。我應該怎麼做?

我做了一些研究和管理,以這樣的運行代碼:

var q = openedDatabase.RecordTable.Where(GetMonthBool); 

static Expression<Func<Record, bool>> GetMonthBool = a => (a.codedID/10000 == 1); 

但expectedValue被硬編碼爲「1」 - 這並沒有解決我的問題。

回答

2

創建,創建這樣的表達

private Expression<Func<Record, bool>> GetMonthBoolFunc(int value) 
{ 
    return a => (a.codedID/10000 == value); 
} 

var q = openedDatabase.RecordTable.Where(GetMonthBoolFunc(1)); 
+0

感謝了很多的方法,它解決了我的問題! :) –