使用LINQ對象列表的更新只有單個項目要更新它具有文本屬性「ALL」我如何在C#
public class Season
{
public string Text {get;set;}
public string Value {get;set;}
public bool ValueSelected {get;set;}
}
使用LINQ對象列表的更新只有單個項目要更新它具有文本屬性「ALL」我如何在C#
public class Season
{
public string Text {get;set;}
public string Value {get;set;}
public bool ValueSelected {get;set;}
}
在LINQ的「Q」列表代表「查詢」。 LINQ並不意味着更新對象。
您可以使用LINQ找到想要更新的對象,然後「傳統地」更新它。
var toUpdate = _seasons.Single(x => x.Text == "ALL");
toUpdate.ValueSelected = true;
此代碼假定恰好有一個進入與Text == "ALL"
。如果沒有或者有多個,此代碼將拋出異常。
如果沒有或一個,使用SingleOrDefault
:
var toUpdate = _seasons.SingleOrDefault(x => x.Text == "ALL");
if(toUpdate != null)
toUpdate.ValueSelected = true;
如果可以有多個,使用Where
:
var toUpdate = _seasons.Where(x => x.Text == "ALL");
foreach(var item in toUpdate)
item.ValueSelected = true;
感謝您的努力,因爲我對開發非常陌生,我無法正確發佈代碼。我已經通過傳統方法 – Gowtham
你可以使用這樣的事情:
// 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");
我只有一個季節項目與「所有」我想只更新該項目,其餘項目是保持不變 – Gowtham
你是什麼意思更新? – spajce
問題需要澄清。這裏是一個基本的LINQ教程http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b –