2

原来的

我不明白为什么 Where() 子句在最后一个示例中没有给我正确的结果。
没什么不同吧?为什么 C# 的行为不同?

transactions = IEnumerable<Transaction> //pseudocode 

//This works: It gives me the transaction I need.
DateTime startDate = DateTime.Parse(parameter.Constraint); 
transactions = transactions.Where(T => T.date >= startDate);  

//This doesn't work... No actual code changed, only the way of writing it...
//I get 0 results.
 transactions = transactions.Where(T => T.date >= DateTime.Parse(parameter.Constraint));

编辑

好的,确实需要提到事务是使用实体框架加载的。

transactions = this.db.Include("blablabla").OrderByDescending(T => T.date);

也许这就是它奇怪的原因?因为 Entity Linq 的工作方式?

4

3 回答 3

5

实际发生这种情况的唯一方法是,如果您正在修改parameterparameter.Constraint以某种方式在枚举transactions. 所以如果你不这样做,看看你是否真的在观察你认为你在观察的东西。

原则上,这应该可以正常工作。

编辑:你可能会对你的观察感到困惑的一种明显方式是,如果你Where直到后来才检查(实际评估)惰性枚举的结果,当parameter发生变化时。如果您将 aToArray放在末尾以立即对其进行评估,您可能会发现它“神奇地”修复了自己。

于 2009-11-24T21:29:32.243 回答
1

我刚试过这个,它工作正常:

class Program
{
    public class Transaction { public DateTime date { get; set; } }
    public class Parameter { public string Constraint { get; set; } }
    public static void Main()
    {
        IEnumerable<Transaction> transactions = new List<Transaction> {
            new Transaction { date = new DateTime(2009, 10, 5) },
            new Transaction { date = new DateTime(2009, 11, 3) }
        };
        Parameter parameter = new Parameter { Constraint = "2009-11-01" };
        DateTime startDate = DateTime.Parse(parameter.Constraint);

        // Version 1.
        transactions = transactions.Where(T => T.date >= startDate);

        // Version 2.
        transactions = transactions.Where(T => T.date >= DateTime.Parse(parameter.Constraint));

    }
}

You must be omitting an important detail. Perhaps you could try reducing your code to the simplest possible example that still reproduces the bug. In doing so, you will probably discover the solution. If you still can't see the problem you can post the short, compiling, non-working version here and I'm sure someone will spot the problem quickly.

于 2009-11-24T21:35:02.977 回答