7

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.

2
  • 2
    Don't abuse LINQ to modify collection. It a query tool. Your approach is not more readable than a foreach but it's much less efficient. Commented Aug 23, 2013 at 12:35
  • Then it should be a lamda expression that can work? or any other way, or i need to loop it after taking object. Commented Aug 23, 2013 at 12:36

1 Answer 1

16

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

Sign up to request clarification or add additional context in comments.

12 Comments

But i am sure the list will be holding one record, so i need to loop it with foreach.?
@NoviceToDotNet: If you're sure it will only have one record, then you should use the methods like FirstOrDefault, First, SingleOrDefault, or Single (whichever is most applicable) rather than creating a list.
@NoviceToDotNet: This is the first you've mentioned of there only being one match. How were we meant to know that? Your original code was looping (with ForEach) so I naturally assumed you needed to loop.
@JonSkeet: Yeah, if you got a reputation each time someone did that, then you'd have hit 600,000k reputation by now. :)
so you mean i should fetch with single statemebt to an object of that type and making changes and replace the object again.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.