在List< T>中设置多个属性. ForEach()? [英] Set multiple properties in a List<T> ForEach()?

查看:183
本文介绍了在List< T>中设置多个属性. ForEach()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上课:

class foo
{
    public string a = "";
    public int b = 0;
}

然后列出它们的通用列表:

Then a generic list of them:

var list = new List<foo>(new []{new foo(), new foo()});

如果我要在下面的List<T> ForEach()方法内分配多个属性,下面是否有更简单的方法来做到这一点?希望我有点胖.

If I am to assign multiple properties inside the following List<T> ForEach() method, is there a simpler way to do it that below? Hopefully I'm being a bit thick.

// one property - easy peasy
list.ForEach(lambda => lambda.a="hello!");
// multiple properties - hmm
list.ForEach(lambda => new Action(delegate() { lambda.a = "hello!"; lambda.b = 99;}).Invoke());

ForEach()实际上是List<T>哎呀的一部分时,以为ForEach()是LINQ扩展方法!

Thought ForEach() was a LINQ extension method, when it's actually part of List<T> oops!

推荐答案

您需要做的就是引入一些方括号,以便您的匿名方法可以支持多行:

All you need to do is introduce some brackets so that your anonymous method can support multiple lines:

list.ForEach(i => { i.a = "hello!"; i.b = 99; });

这篇关于在List&lt; T&gt;中设置多个属性. ForEach()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆