【问题标题】:Expression is not filtering immediately表达式没有立即过滤
【发布时间】:2015-03-31 23:29:33
【问题描述】:

请参阅下面的示例。 LINQ 表达式要求 _Age 在 15 到 20 之间的 Student 对象列表。当我在调试器中看到 varlist 时,它显示 5 个条目。当我打印 varlist 时,它只打印一个条目,这是正确的。即使在打印之后,调试器也会在 varlist 中显示 5 个条目。这种行为是否记录在任何地方,请告诉我。 列表中是否应该有很多条目(例如数百万),以便 LINQ 表达式实际过滤项目。

public class Student
{
    public int StudentID { get; set; }
    public String StudentName { get; set; }
    public int Age { get; set; }
}

static void Main(string[] args)
{
    IList<Student> studentList = new List<Student>
    { 
        new Student { StudentID = 1, StudentName = "John", Age = 13 }, 
        new Student { StudentID = 2, StudentName = "Moin", Age = 21 }, 
        new Student { StudentID = 3, StudentName = "Bill", Age = 18 }, 
        new Student { StudentID = 4, StudentName = "Ram", Age = 20 }, 
        new Student { StudentID = 5, StudentName = "Ron", Age = 15 }
   };

    IEnumerable<Student> varlist = from rv in studentList
                                   where rv.Age > 15 && rv.Age < 20
                                   select rv;
    foreach (Student x in varlist)
    {
        Console.WriteLine("{0} {1}", x.Age, x.StudentName);
    }
}

【问题讨论】:

  • 为什么你会期望超过 5 个输出?
  • 因为 varList 是 IQueryable 对象,并且为了检查结果应该通过循环或转换为列表来使用列表。如果您调用 Varlist.ToList() 则请参阅仅返回一个对象
  • 这就是LINQ的特点。
  • 佩曼,你的回答解决了它。我调用了 ToList(),结果只显示了一个条目。也感谢 youGrant。

标签: c# linq where-clause


【解决方案1】:

这就是延迟执行与 Linq 一起工作的方式。 Linq 查询后面有一个表达式树,因此您可以将 Linq 查询视为一种数据结构。在您请求数据之前,您的查询不会执行,当编译该表达式时,当您枚举它时会发生这种情况。

您可以在此处阅读更多信息:

http://blogs.msdn.com/b/charlie/archive/2007/12/09/deferred-execution.aspx

IEnumerable<Customer> query = from customer in db.Customers  << Query does  
        where customer.City == "Paris" << not execute
        select customer;               << here 


foreach (var Customer in query) << Query executes here

无论您使用 IEnumerable 还是 IQueryable 来表示查询变量,都将使用延迟执行:

Returning IEnumerable<T> vs. IQueryable<T>

【讨论】:

    【解决方案2】:

    LINQ 的理念是您可以在实际执行之前在其之上添加操作。

    如果你想强制LINQ计算结果,你可以使用ToArray()

    var arr = seq.ToArray();
    

    【讨论】:

      猜你喜欢
      • 2013-04-10
      • 1970-01-01
      • 2013-10-16
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多