我有一个来自数据库的产品列表,从这个列表中,我使用LINQ并返回电话类列表。
List<Product> products = new List<Product>
{
new Product { ID = 1, Name = "Alcohol", Expired = false },
new Product { ID = 2, Name = "Phone", Expired = false },
new Product { ID = 2, Name = "Phone", Expired = false },
new Product { ID = 3, Name = "Computer", Expired = false },
new Product { ID = 4, Name = "Chair", Expired = false },
};
var results = from i in products.Where(o => o.Name == "Phone")
select new Phones
{
ID = i.ID,
Phone = i.Name,
isChild = i.Expired
};
//Update the isChild property
foreach (var item in results)
{
item.isChild = true;
}
public class Phones
{
public int ID { get; set; }
public string Phone { get; set; }
public bool isChild { get; set; }
}
我曾经使用foreach循环更新手机列表。但问题是,当我检查结果变量时,它不会更新上述项目。
答案 0 :(得分:1)
这是因为IEnumerable的延迟执行。尝试将结果转换为ToList以立即执行该查询:
var results = (from i in products.Where(o => o.Name == "Phone")
select new Phones
{
ID = i.ID,
Phone = i.Name,
isChild = i.Expired
}).ToList();
如果你不知道 - 每次都会重新询问产品,你会使用一套新的手机。