简体   繁体   English

C#foreach将list属性设置为使用list在一行中循环索引。

[英]C# foreach set list property to loop index in one line using list.Foreach

int loopIndex = 0;
foreach (var item in dataList)
{
    item.ChannelId = loopIndex;
    loopIndex++;
}

I am looking for an alternate of above code in one line. 我在一行中寻找上述代码的替代形式。 Something like- dataList.ForEach(x=>x.ChannelId=...) dataList.ForEach(x=>x.ChannelId=...)

Suggestions please. 请提出建议。

如果您使用NuGet Microsoft的“ System.Interactive”扩展,则可以执行以下操作:

dataList.ForEach((item, index) => item.ChannelId = index);

Here is a Linq appraoch in one line without the requiremet to install another library 这是一行中的Linq方法,无需安装另一个库

dataList = dataList.Select((x, i) => { x.ChannelId = i; return x; }).ToList();

Code: https://dotnetfiddle.net/SCEbyV 代码: https//dotnetfiddle.net/SCEbyV


another appraoch - the classy for loop way in one line 另一个方法-一行中经典for循环方式

for (int i = 0; i < dataList.Count; i++) dataList[i].ChannelId = i;

尝试这个

dataList.ForEach(x => x.ChannelId = loopIndex++);

尝试这个

dataList= dataList.Select(x=>x.ChannelId=loopIndex++).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM