Reputation: 803
I am trying to update the items in a list with user provided parameters. I am using a custom list type AbilityScores
. See below:
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; }
}
I am trying to add the update a specific part of the list:
if(ability == "Strength"){
abilityScores.Where(w => w.Strength == "Strength").ToList().ForEach(s => s.Strength = scoreIncrease.ToString());
}
Both ability
and scoreIncrease
are user provided parameters. Here I am updating the strength attribute. I understand most of what I read here:
But I do not understand what w => w.Strength == "Strength"
is actually doing. How would I use this in my code? I am really new to C# and lists. Any help would be greatly appreciated.
Upvotes: 0
Views: 403
Reputation: 37367
You could try iterating over subset of your list specified by Where
:
foreach(var s in abilityScores.Where(w => w.Strength == ability))
s.Strength = scoreIncrease.ToString();
Upvotes: 0
Reputation: 1671
You are using a linq statement. It does the same as the following traditional way:
if (ability == "Strength")
{
foreach (var abilityScore in abilityScores)
{
if (abilityScore.Strength == "Strength")
{
abilityScore.Strength = scoreIncrease.ToString();
}
}
}
Upvotes: 0
Reputation: 15
w => w.Strength == "Strength"
compares on every item in the list, whatever is property Strength
equal to string "Strength"
. Where function uses lambda expression for criteria which part of list you want to select.
More about lambda expression: https://weblogs.asp.net/dixin/understanding-csharp-features-5-lambda-expression
Upvotes: 0
Reputation: 7204
You don't need the Where
at all. It is used when you want to filter somes item by a condition defined by a Predicate
In your case, you want to update the value Strength
for all objects.
Using a ForEach
is enough
foreach(var s in abilityScores)
{
s.Strength = scoreIncrease.ToString()
}
Upvotes: 2