选择投影中的索引

dex*_*ter 11 c# linq ienumerable select

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

var dataSource = WebConfigurationHelper.GetSupportedDomainsString().Select((domain, index) => 
new { index , Name = domain });
Run Code Online (Sandbox Code Playgroud)

所以我的输出成为:

index=2 domain=zombieland
index=3 domain=mydomain
Run Code Online (Sandbox Code Playgroud)

有可能吗?

Jon*_*eet 18

您可以在"选择"投影中进行调整:

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

我原来的建议,理由new { index + 2, Name = domain }是行不通的是,投影初始化时,表达的是一种"简单的名字"(其中仅指定一个表达式,让编译器推断名)才能正常运行,一个"成员访问"或"基本访问".