Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the list value using linq

Tags:

class

linq

c#-3.0

Hi I want to set the value in the list of objects that matches the given condition in the where clause.Is it possible? Other work around is to get the list of objects using where clause and then iterate using for Or foreach loop and update the value.

listOfRequestAssigned.Where(x => x.RequestedNumber == CurrentRequest);

I have list listOfRequestAssigned of objects and want to update some propery of the objects that match my search criteria.

class Request
 {
 bool _requestCompleted;
   int _requestedNumber;
     public int RequestedNumber 
    {
        get { return _requestedNumber; }
        set { _requestedNumber = value; }
    }
    public bool RequestCompleted
    {
        get { return _requestCompleted; }
        set { _requestCompleted = value; }
    }
 }

I want to update RequestCompleted property of all objects that match criteria using Linq

like image 484
lokendra jayaswal Avatar asked Oct 12 '25 00:10

lokendra jayaswal


2 Answers

You can use ForEach in Linq

listOfRequestAssigned.Where(x => x.RequestedNumber == CurrentRequest).ToList().ForEach(x => x.RequestCompleted = true);

if you have more than one update to do,

listOfRequestAssigned.Where(x => x.RequestedNumber == CurrentRequest).ToList().ForEach(x =>  { x.RequestCompleted = true; x.OtherProperty = value; } );

Where(...) give you a query, not a Request or a List<Request>. Use FirstOrDefault() if you want to have one (or 0) result, or ToList() if you want to have a list of results on wich you can use ForEach().

like image 63
Xaruth Avatar answered Oct 15 '25 14:10

Xaruth


In general Linq is a query- not an update tool, but you can use a foreach:

var currentRequests =  listOfRequestAssigned
    .Where(x => x.RequestedNumber == CurrentRequest);
foreach(var req in currentRequests)
{
    req.RequestCompleted = true;
}
like image 44
Tim Schmelter Avatar answered Oct 15 '25 15:10

Tim Schmelter