I want to do something like this
foreach (var item in SeasonList)
{
if (item.Text == "ALL")
{
item.IsSelected = true;
}
}
# Custom foreach loop behaviour with C# LINQ methods The foreach loop makes it easy to loop through a collection. Its loop variable gives convenient access to each element's value. And there's no index variable to manage.
A new List, yes - but containing the same items, which will be updated correctly. This new list is then discarded. Also, Linq is only used here to loop over the collection, just like wudzik's answer. The i.age = 10 part is not different from the item.age = 10 part. In both cases , the update is not done with Linq :)
Another option is to use LINQ's Select method. Normally, all we ask the Select method to do is return the object that will make up the new collection -- in fact, the Select method insists that the lambda expression passed to it return an object.
Note though, that this is a List extension method in the same System.Collections.Generic as List itself. So there is nothing Linq about this method or syntax, it just looks like Linq. The example above will perform the WriteLine method on every item in a list. Sometimes though, you only want to perform such an action on certain items.
foreach(var item in SeasonList.Where(x => x.Text == "ALL"))
{
item.Selected = false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With