将值分配给lambda表达式之外的变量

时间:2011-05-11 00:59:21

标签: c# linq

我想为一个位于lambda表达式之外的变量赋值。例如。

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还包含SelectedCategory的属性,如果CategoryName,我想将c.CategoryId == cat分配给它。我该怎么做?

3 个答案:

答案 0 :(得分:4)

我对这种编程风格并不感到骄傲,因为它很快变得难以理解,但在某些情况下它可能很有用:

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

答案 1 :(得分:2)

之后我会做这样的事情:

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

理想情况下,我只是将SelectedCategory设置为动态返回的属性,而不是可能不同步的设置值:

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

答案 2 :(得分:0)

我不认为可以在该查询中完成。我担心它必须在单独的查询中;这样的事情(分配model.Categories后)

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