Is it possible to manipulate lists using LINQ?

This may be a dumb question, but I always used linq to select items.

But I want to know if the following simple task can be done with my keywords.

List<OrdersInfo> ordersList . . . foreach(OrdersInfo OI in ordersList) if(OI.TYPE == "P") OI.TYPE = "Project"; else OI.TYPE = "Support"; 
+6
source share
4 answers

No, LINQ (Language-Integrated Query) is a query language, and it really shines in a specific query definition, but is not always good at it (speed and / or memory problem).

If you want to change the collection, stay with how you already do it.

+4
source

You can use the ForEach method of the List class.

 ordersList.ForEach(oi => oi.TYPE = oi.TYPE == "P" ? "Project" : "Support" ); 

If you want to have a ForEach method in IEnumerable type, you can create your own ForEach extension

 public static void ForEach<T>(this IEnumerable<T> en, Action<T> action) { foreach(T item in en) { action(item); } } 
+6
source

LINQ is for querying the collection. To change, your current loop is a more readable and better approach, but if you want a LINQ option, then:

If OrderInfo is a class (reference type), you can change the properties of the object (you cannot set them to null or new links).

 var ordersList = new List<OrdersInfo>(); ordersList.Add(new OrdersInfo() { TYPE = "P" }); ordersList.Add(new OrdersInfo() { TYPE = "S" }); ordersList.Add(new OrdersInfo() { TYPE = "P" }); ordersList.Select(r => (r.TYPE == "P" ? r.TYPE = "Project" : r.TYPE = "Support")).ToList(); 

With your class it is defined as:

 class OrdersInfo { public string TYPE { get; set; } } 

Here is a screenshot enter image description here

Interestingly, I did not assign the result back to ordersList

+1
source

ForEach is not a Linq solution, but it looks like this:

 ordersList.ForEach(OI => OI.TYPE = OI.TYPE == "P" ? "Project" : "Support"); 

Available ony on an instance of List<T> , not on IEnumerable<T> .

+1
source

Source: https://habr.com/ru/post/943529/


All Articles