Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set multiple values in a list using lambda expression?

Tags:

c#

linq

How to set multiple values of a list object, i am doing following but fails.

objFreecusatomization
.AllCustomizationButtonList
.Where(p => p.CategoryID == btnObj.CategoryID && p.IsSelected == true && p.ID == btnObj.ID)
.ToList()
.ForEach(x => x.BtnColor = Color.Red.ToString(),  );

In the end after comma i want to set another value. What should be the expression, although i have only one record relevant.

like image 694
NoviceToDotNet Avatar asked Aug 23 '13 12:08

NoviceToDotNet


1 Answers

Well personally I wouldn't write the code that way anyway - but you can just use a statement lambda:

A statement lambda resembles an expression lambda except that the statement(s) is enclosed in braces

The body of a statement lambda can consist of any number of statements; however, in practice there are typically no more than two or three.

So the ForEach call would look like this:

.ForEach(x => {
    x.BtnColor = Color.Red.ToString();
    x.OtherColor = Color.Blue.ToString();
});

I would write a foreach loop instead though:

var itemsToChange = objFreecusatomization.AllCustomizationButtonList
     .Where(p => p.CategoryID == btnObj.CategoryID
                 && p.IsSelected
                 && p.ID == btnObj.ID);

foreach (var item in itemsToChange)
{
    item.BtnColor = Color.Red.ToString();
    item.OtherColor = Color.Blue.ToString();
}

(You can inline the query into the foreach statement itself, but personally I find the above approach using a separate local variable clearer.)

like image 57
Jon Skeet Avatar answered Oct 31 '22 22:10

Jon Skeet