Ahmet
Ahmet

Reputation: 41

How to replace values smaller than zero with zero in a collection using LINQ

I have a list of objects. This object has a field called val. This value shouldn't be smaller than zero but there are such objects in this list. I want to replace those less-than-zero values with zero. The easiest solution is

foreach(Obj item in list)
{
    if (item.val < 0)
    {
        item.val = 0;
    }
}

But I want to do this using LINQ. The important thing is I do not want a list of updated elements. I want the same list just with the necessary values replaced. Thanks in advance.

Upvotes: 0

Views: 969

Answers (3)

Baskovli
Baskovli

Reputation: 640

loop 'for' is faster than 'foreach' so you can use this one

          for (int i = 0; i < list.Count; i++)
            {
                if(list[i].val <= 0)
                {
                    list[i].val = 0;
                }
            }

Upvotes: 1

Pashyant Srivastava
Pashyant Srivastava

Reputation: 665

you can try this one, which is faster because of parallelism

Parallel.ForEach(list, item =>
{
    item.val = item.val < 0 ? 0 : item.val;
});

The Parallel ForEach in C# provides a parallel version of the standard, sequential Foreach loop. In standard Foreach loop, each iteration processes a single item from the collection and will process all the items one by one only. However, the Parallel Foreach method executes multiple iterations at the same time on different processors or processor cores. This may open the possibility of synchronization problems. So, the loop is ideally suited to processes where each iteration is independent of the others

More Details - LINK

Upvotes: 1

Ahmet
Ahmet

Reputation: 41

As I read the comments I realized what I wanted to do is less efficient and pointless. LINQ is for querying and creating new collections rather than updating collections. A possible solution I came across was this

list.Select(c => { if (c.val < 0 ) c.val= 0; return c;}).ToList();

But my initial foreach solution is more efficient than this. So dont make the same mistake I do and complicate things.

Upvotes: 2

Related Questions