我正在尝试使用用户提供的参数更新列表中的项目。我使用自定义列表类型AbilityScores
。见下文:
class AbilityScores
{
public string Strength { get; set; }
public string Dexterity { get; set; }
public string Constitution { get; set; }
public string Intelligence { get; set; }
public string Wisdom { get; set; }
public string Charisma { get; set; }
}
我正在尝试将更新添加到列表的特定部分:
if(ability == "Strength"){
abilityScores.Where(w => w.Strength == "Strength").ToList().ForEach(s => s.Strength = scoreIncrease.ToString());
}
ability
和scoreIncrease
都是用户提供的参数。我在这里更新strength属性。我理解我在这里读到的大部分内容:
但我不明白w => w.Strength == "Strength"
究竟在做什么。我如何在我的代码中使用它?我是C#和列表的新手。任何帮助将不胜感激。
你根本不需要Where
。当您想要按照Predicate定义的条件过滤某些项目时使用它
在您的情况下,您想要更新所有对象的值Strength
。
使用ForEach
就足够了
foreach(var s in abilityScores)
{
s.Strength = scoreIncrease.ToString()
}
w => w.Strength == "Strength"
c比较列表中的每个项目,无论属性Strength
等于字符串"Strength"
。其中函数使用lambda表达式作为要选择的列表部分的条件。
关于lambda表达式的更多信息:https://weblogs.asp.net/dixin/understanding-csharp-features-5-lambda-expression
您正在使用linq语句。它与以下传统方式相同:
if (ability == "Strength")
{
foreach (var abilityScore in abilityScores)
{
if (abilityScore.Strength == "Strength")
{
abilityScore.Strength = scoreIncrease.ToString();
}
}
}
您可以尝试迭代Where
指定的列表的子集:
foreach(var s in abilityScores.Where(w => w.Strength == ability))
s.Strength = scoreIncrease.ToString();