【问题标题】:LINQ "where" with parameter带有参数的 LINQ“位置”
【发布时间】:2012-09-27 19:30:32
【问题描述】:

我确定这是菜鸟的错误,但我自己找不到答案。

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” - 这并不能解决我的问题。

【问题讨论】:

    标签: c# sql linq linq-to-sql lambda


    【解决方案1】:

    创建一个方法来创建这样的表达式

    private Expression<Func<Record, bool>> GetMonthBoolFunc(int value)
    {
        return a => (a.codedID/10000 == value); 
    }
    
    var q = openedDatabase.RecordTable.Where(GetMonthBoolFunc(1)); 
    

    【讨论】:

      猜你喜欢
      • 2011-03-20
      • 1970-01-01
      • 2017-05-04
      • 1970-01-01
      • 1970-01-01
      • 2012-09-02
      • 1970-01-01
      • 2015-11-07
      相关资源
      最近更新 更多