【问题标题】:Index in the Select projection选择投影中的索引
【发布时间】:2011-06-17 08:00:07
【问题描述】:

我希望我的索引从大于 0 的数字开始,同时执行以下操作:

var dataSource = WebConfigurationHelper.GetSupportedDomainsString().Select((domain, index) => 
new { index , Name = domain });

所以我的输出变成:

index=2 domain=zombieland
index=3 domain=mydomain

可以吗?

【问题讨论】:

    标签: c# linq select ienumerable


    【解决方案1】:

    您可以在选择投影中调整它:

    var dataSource = WebConfigurationHelper.GetSupportedDomainsString()
         .Select((domain, index) =>  new { Index = index + 2, Name = domain });
    

    我最初对 new { index + 2, Name = domain } 的建议不起作用的原因是 投影初始化器(您只指定一个表达式,并让编译器推断名称)仅在表达式为“简单名称”、“成员访问”或“基本访问”。

    【讨论】:

    • 我几乎觉得问起来很愚蠢,但没有我试过 - 我得到“无效的匿名类型成员装饰器”波浪线错误,但后来这工作:var dataSource = WebConfigurationHelper.GetSupportedDomainsString().Select ((domain, index) => new { Index = index + 2, Name = domain });
    • @Max Malygin:编译器不会为您从index + 2 推断名称;您必须明确命名该成员。
    猜你喜欢
    • 1970-01-01
    • 2015-02-01
    • 1970-01-01
    • 2010-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-09
    • 2020-07-20
    相关资源
    最近更新 更多