Answered by:
c# replace negative list items with 0

Question
-
I have a list and I want to replace negative list items with 0.
I've tried something, but it doesn't work:
List<decimal> value = new List<decimal>();
value .Where(x => x <0).ToList().ForEach(s => s.Value = 0);
or
foreach (double v in value) if (v< 0) Math.Max(0, v);
Friday, September 18, 2015 5:26 AM
Answers
-
Hi,
Please refer code below:
List<decimal> value2 = value.Select(x => (x < 0 ? 0 : x)).ToList();
Thanks
- Proposed as answer by Fouad Roumieh Friday, September 18, 2015 12:35 PM
- Marked as answer by Kristin Xie Monday, September 28, 2015 9:43 AM
Friday, September 18, 2015 6:47 AM
All replies
-
Try this:
List<decimal> list = new List<decimal>();
. . .
for( int i = 0; i < list.Count; ++i ) list[i] = Math.Max( 0, list[i] );If you want to preserve the original list and create a second one, then:
List<decimal> list2 = list.Select( v => Math.Max( 0, v ) ).ToList();
Friday, September 18, 2015 6:02 AM -
for (int i = 0; i < value.Count; i++)
{
if (value[i] < 0)
{
value[i] = 0;
}
//MessageBox.Show(value[i].ToString());
}Friday, September 18, 2015 6:39 AM -
I am not sure if using LINQ is a good idea to replace a collection but you can try this:
List<decimal> myList = new List<decimal>(); myList.Add(5); myList.Add(1); myList.Add(-55); List<decimal> output = new List<decimal>(); myList = output.Concat(myList.Where(x => x < 0).Select(x => x - x).ToList().Concat(myList.Where(x => x > 0)).ToList()).ToList();
The items of the myList will be 5,1, 0
Friday, September 18, 2015 6:40 AM -
Hi,
Please refer code below:
List<decimal> value2 = value.Select(x => (x < 0 ? 0 : x)).ToList();
Thanks
- Proposed as answer by Fouad Roumieh Friday, September 18, 2015 12:35 PM
- Marked as answer by Kristin Xie Monday, September 28, 2015 9:43 AM
Friday, September 18, 2015 6:47 AM -
Hi,
Using for loop, we can achieve this.. Please refer the below code..
List<decimal> decimlaList = new List<decimal> {-1, 0, 3, -1}; for (int index = 0; index < decimlaList.Count; index++) { var value = decimlaList[index]; if (value < 0) { value = 0; } }
The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for loop.
It would be greatly appreciated if you would mark any helpful entries as helpful and if the entry answers your question, please mark it with the Answer link.
- Edited by Sivasankar Gorantla Sunday, September 20, 2015 5:36 AM
Sunday, September 20, 2015 5:33 AM