使用LINQ查询和更新集合中的属性 [英] Query and updating a property in a collection using LINQ

查看:152
本文介绍了使用LINQ查询和更新集合中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用LINQ更新集合中特定项目的单个属性的最简洁/最简单的方法是什么?

What is the most succint/simple way of updating a single property of a specific item within a collection using LINQ?

例如,如果我有以下列表:

For example if I have a List of the following:

public class Ticket
{
    public string Name { get; set; }
    public string Code { get; set; }
    public bool Selected { get; set; }
}

如何使用LINQ更新故障单项目的选定"属性,而其名称"属性的值为海滩".在SQL中为:

How can I use LINQ to update the "Selected" property of a Ticket item wheres its "Name" property has the value of "Beach". In SQL it would be:

UPDATE Tickets SET Selected = true WHERE Name = 'Beach'

我以为我在这个方向上是正确的...

I thought I was on the right track with this...

tickets.Select(x => { x.Selected = true; return x; }).ToList().Where(x => x.Name == "Beach");

推荐答案

您可以更改顺序,然后使用ForEach运算符:

You can change the order, then use the ForEach operator:

tickets
   .Where(x => x.Name == "Beach")
   .ToList()
   .ForEach(x => { x.Selected = true; });

注意:

  • 由于IEnumerable在Linq中不支持ForEach,因此需要ToList()-请参见 LINQ相当于IEnumerable< T>
  • 的foreach
  • 出于可读性考虑,最好将其分离为linq查询,然后再使用更常规的foreach(x in list) C#循环
  • 如果这是linq-to-sql,则需要调用SubmitChanges()才能保留更改.
  • that the ToList() is needed because IEnumerable doesn't support ForEach in Linq - see LINQ equivalent of foreach for IEnumerable<T>
  • that for readability it might be better to separate this out into a linq query and then a more conventional foreach(x in list) C# loop
  • if this is linq-to-sql, then you'll need to call SubmitChanges() in order to persist your changes.

这篇关于使用LINQ查询和更新集合中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆