【发布时间】: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