Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#foreach set list属性使用list.foreach在一行中循环索引_C#_Linq - Fatal编程技术网

C#foreach set list属性使用list.foreach在一行中循环索引

C#foreach set list属性使用list.foreach在一行中循环索引,c#,linq,C#,Linq,我正在寻找一个替代上述代码在一行。类似于-dataList.ForEach(x=>x.ChannelId=…) 请提供建议。这里有一个Linq方法,一行中没有安装另一个库的要求 int loopIndex = 0; foreach (var item in dataList) { item.ChannelId = loopIndex; loopIndex++; } 代码: 另一种方法-一行中的环路的上等 dataList = dataList.Select((x, i) =&

我正在寻找一个替代上述代码在一行。类似于-
dataList.ForEach(x=>x.ChannelId=…)


请提供建议。

这里有一个
Linq
方法,一行中没有安装另一个库的要求

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


另一种方法-一行中的环路的上等

dataList = dataList.Select((x, i) => { x.ChannelId = i; return x; }).ToList();
(int i=0;i
如果您获得了Microsoft的“System.Interactive”扩展,则可以执行以下操作:

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

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

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

为什么它必须是一行?您试图实现什么?dataList是一个包含一个实体的列表@mjwills
dataList.ForEach(item=>{item.ChannelId=loopIndex;loopIndex++;})
@Sayse只是想知道我们是否可以在list.ForEach中为list属性设置循环索引,而不是像我上面使用的那样使用ForEach。MoreLINQ的ForEach可能也值得考虑-。遗憾的是,您需要System.Linq来为任何可枚举的,看起来比其他所有人都好。@DanRayson我不知道
dataList
的类型,但肯定
dataList.Length
dataList.Count
是for循环的数组或列表+1,因为它通常比更优雅的带有索引的ForEach具有更好的性能。有时候这很重要。
dataList= dataList.Select(x=>x.ChannelId=loopIndex++).ToList();