Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: Transforming items in a collection

Tags:

c#

.net

linq

Is there a LINQ method to modify items in a collection, such as simply setting a property of each item in a collection? Something like this:

var items = new []{ new Item { IsActive = true } }
var items = items.Transform(i => i.IsActive = false)

where Touch enumerates each item and applies the transformation. BTW, I am aware of the SELECT extension method, but this would require I expose a method on the type that does this transformation and return the same reference.

var items = items.Select(i => i.Transform())

where Item.Transform returns does the transformation and return the same instance.

TIA

like image 724
Klaus Nji Avatar asked Oct 15 '11 18:10

Klaus Nji


People also ask

What collections can LINQ be used with?

You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey,TValue>. The collection may be user-defined or may be returned by a . NET API.

Which method of C #' s LINQ can be used to transform one type of parameter into another?

By using a LINQ query, you can use a source sequence as input and modify it in many ways to create a new output sequence. You can modify the sequence itself without modifying the elements themselves by sorting and grouping.

How do I return a single value from a list using LINQ?

var fruit = ListOfFruits. FirstOrDefault(x => x.Name == "Apple"); if (fruit != null) { return fruit.ID; } return 0; This is not the only road to Rome, you can also use Single(), SingleOrDefault() or First().


2 Answers

No, there are no methods in standard LINQ that allows you to modify items in a collection. LINQ is for querying collections and not for causing side-effects (e.g., mutating the items). Eric Lippert goes into the idea in more detail in his blog post: “foreach” vs “ForEach”.

Just use a loop.

foreach (var item in items)
{
    item.IsActive = false;
}
like image 120
Jeff Mercado Avatar answered Sep 27 '22 22:09

Jeff Mercado


LINQ is for querying. Use a simple loop if you want to modify. Just use the right tool for the right job. LINQ is not a messiah for everything.

like image 42
Darin Dimitrov Avatar answered Sep 27 '22 23:09

Darin Dimitrov