foreach (var item in items)
{
item.category = "All Items";
}
How to replace the above foreach with Linq.
I have tried with following code, but it returns null for the item
_ = items.Select(x => x.item = "All Items")
Note : items
is of type IEnumerable<ItemList>
CodePudding user response:
linq is an example of functional programming - in general it does not change the input data it reads it in and outputs new data
you can do this (assuming you have a List to start with)
items = items.Select(item=>item.category = "All Items").ToList();
CodePudding user response:
You can use the Select method with a lambda expression to modify each item in the items collection, like this:
items = items.Select(x => { x.category = "All Items"; return x; });
or use Select method with an anonymous method
items = items.Select(delegate(ItemList x) { x.category = "All Items"; return x; });
Or you can use ForEach method like
items.ToList().ForEach(x => x.category = "All Items");
You can also use ForEach extension method like
items.ToList().ForEach(x => x.category = "All Items");
Note that, ForEach is not a linq method, it is an extension method of List, it works on in-memory collection and executes the lambda expression for each element of the collection.