Pawan Lakhara
Pawan Lakhara

Reputation: 1150

How to update an item in a List using LINQ

I have a List<>

I need to modify single row item of the list.

List.Where(x => x.Amount>0).OrderBy(x => x.Id).ToList()
.ForEach(x => x.Amount = x.Amount + (item1- item2));

Above code is work for multiple rows but I want to select the first row of the list using conditions and update or modified only first-row item value.

Thanks

Upvotes: 1

Views: 19984

Answers (2)

Afonso
Afonso

Reputation: 338

Do you mean something like this

List.Where(x => x.Amount>0).OrderBy(x => x.Id).FirstOrDefault()?.Amount += (item1- item2);

Upvotes: 4

CodeNotFound
CodeNotFound

Reputation: 23240

So you can just use FirstOrDefault extension method like below:

var item = List.FirstOrDefault(x => x.Amount > 0);
if (item != null) 
{
    item.Amount += item1- item2;
}

Side Note: the condition is a bit weird. The first row returned can be different on each time you execute the query.

Upvotes: 4

Related Questions