Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update List<T> using foreach loop and Condition using LINQ/LAMBDA [duplicate]

Tags:

c#

I want to do something like this

foreach (var item in SeasonList)
{
    if (item.Text == "ALL")
    {
        item.IsSelected = true;
    }
}
like image 986
Dangerous Dev Avatar asked Feb 06 '13 13:02

Dangerous Dev


People also ask

What is the purpose of the foreach loop in LINQ?

# 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.

Can LINQ be used to update a list?

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 :)

How to create a collection from a lambda expression in 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.

Is there a list extension method with LINQ?

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.


1 Answers

foreach(var item in SeasonList.Where(x => x.Text == "ALL"))
{
    item.Selected = false;
}
like image 180
Aron Avatar answered Sep 29 '22 02:09

Aron