如何在 C# 中使用 LINQ 更新对象列表的单个项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14729239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to update a single item of liist of objects using LINQ in C#
提问by Gowtham
I want like to update the Value
of the list which hast property Text="ALL"
.
我想更新具有Value
属性的列表Text="ALL"
。
public class Season
{
public string Text {get;set;}
public string Value {get;set;}
public bool ValueSelected {get;set;}
}
采纳答案by Daniel Hilgarth
The 'Q' in LINQ stands for "Query". LINQ is not meant to update objects.
LINQ 中的“Q”代表“查询”。LINQ 不是用来更新对象的。
You can use LINQ to find the object you want to update and then update it "traditionally".
您可以使用 LINQ 查找要更新的对象,然后“传统地”更新它。
var toUpdate = _seasons.Single(x => x.Text == "ALL");
toUpdate.ValueSelected = true;
This code assumes that there is exactly oneentry with Text == "ALL"
. This code will throw an exception if there is none or if there are multiple.
此代码假定只有一个条目带有Text == "ALL"
. 如果没有或有多个,此代码将引发异常。
If there is either none or one, use SingleOrDefault
:
如果没有或有,请使用SingleOrDefault
:
var toUpdate = _seasons.SingleOrDefault(x => x.Text == "ALL");
if(toUpdate != null)
toUpdate.ValueSelected = true;
If it's possible that there are multiple, use Where
:
如果可能有多个,请使用Where
:
var toUpdate = _seasons.Where(x => x.Text == "ALL");
foreach(var item in toUpdate)
item.ValueSelected = true;
回答by Dennisch
You could use something like this:
你可以使用这样的东西:
// Initialize test list.
List<Season> seasons = new List<Season>();
seasons.Add(new Season()
{
Text = "All"
});
seasons.Add(new Season()
{
Text = "1"
});
seasons.Add(new Season()
{
Text = "2"
});
seasons.Add(new Season()
{
Text = "All"
});
// Get all season with Text set to "All".
List<Season> allSeasons = seasons.Where(se => se.Text == "All").ToList();
// Change all values of the selected seasons to "Changed".
allSeasons.ForEach(se => se.Value = "Changed");