Shawn Mclean
Shawn Mclean

Reputation: 57469

Assign values to variables outside of the lambda expression

I want to assign a value to a variable thats located outside of the lambda expression. For eg.

model.Categories =
   productService.GetAllCategories().Select(
      c => new CategoryViewModel 
      {
          CategoryId = c.CategoryId, 
          CategoryName = c.CategoryName, 
          IsSelected = c.CategoryId == cat 
          //how can i also assign the CategoryName to model.SelectedCategory?
      }).ToList();

model also contains a property of SelectedCategory, which I want to assign the CategoryName to it if c.CategoryId == cat. How do I do this?

Upvotes: 0

Views: 1616

Answers (3)

Bala R
Bala R

Reputation: 108957

I don't think it can be done in that query. I'm afraid it is going to have to be in a seperate query; something like this (after model.Categories is assigned)

var selectedCategory = model.Categories.SingleOrDefault(c => c.IsSelected);
if(selectedCategory != null)
{ 
    model.SelectedCategory = selectCategory.CategoryName;
}

Upvotes: 0

Rick Sladkey
Rick Sladkey

Reputation: 34240

I'm not crazy about this style of programming as it quickly becomes unreadable but it can be useful in some situations:

model.Categories =
    productService.GetAllCategories().Select(
        c =>
            {
                if (c.CategoryId == cat)
                    model.SelectedCategory = c.CategoryName;
                return new CategoryViewModel
                {
                    CategoryId = c.CategoryId,
                    CategoryName = c.CategoryName,
                    IsSelected = c.CategoryId == cat
                }
            }).ToList();

Upvotes: 4

Matt Mitchell
Matt Mitchell

Reputation: 41823

I'd just do something like this afterwards:

model.SelectedCategory = model.Categories.Single(c => c.IsSelected).CategoryName;

Ideally though, I'd just have SelectedCategory be a property dynamically returning that, rather than a set value that could fall out of sync:

public string SelectedCategory
{
    get 
    {
        Category selected = Categories.SingleOrDefault(c => c.IsSelected);
        return (selected != null ? selected.CategoryName : String.Empty);
    }
}

Upvotes: 2

Related Questions