为 lambda 表达式之外的变量赋值
我想为位于 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
的属性,如果 c.CategoryId == cat
,我想将 CategoryName
分配给它代码>.我该怎么做?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为在该查询中无法完成此操作。恐怕它必须在一个单独的查询中;像这样的东西(在分配
model.Categories
之后)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)我并不热衷于这种编程风格,因为它很快就会变得不可读,但在某些情况下它可能很有用:
I'm not crazy about this style of programming as it quickly becomes unreadable but it can be useful in some situations:
之后我会做这样的事情:
不过理想情况下,我只是让 SelectedCategory 成为动态返回该属性的属性,而不是可能不同步的设置值:
I'd just do something like this afterwards:
Ideally though, I'd just have SelectedCategory be a property dynamically returning that, rather than a set value that could fall out of sync: