微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 如何使用lambda表达式在列表中设置多个值?

如何设置列表对象的多个值,我正在做以下但失败.
objFreecusatomization
.AllCustomizationButtonList
.Where(p => p.CategoryID == btnObj.CategoryID && p.IsSelected == true && p.ID == btnObj.ID)
.ToList()
.ForEach(x => x.BtnColor = Color.Red.ToString(),);

在逗号后我想要设置另一个值.
应该是什么表达,虽然我只有一个记录相关.

解决方法

好吧,我个人也不会那样编写代码 – 但你可以使用 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.

所以ForEach调用看起来像这样:

.ForEach(x => {
    x.BtnColor = Color.Red.ToString();
    x.OtherColor = Color.Blue.ToString();
});

我会写一个foreach循环,但是:

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

(您可以将查询内联到foreach语句本身,但我个人发现上面的方法使用单独的局部变量更清晰.)

原文地址:https://www.jb51.cc/csharp/98529.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐