开发者

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, 开发者_Python百科
          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?


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();


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);
    }
}


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜