NoviceToDotNet
NoviceToDotNet

Reputation: 10805

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

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.

Upvotes: 7

Views: 13115

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500055

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.)

Upvotes: 16

Related Questions