Reputation: 1326
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=...)
Suggestions please.
Upvotes: 1
Views: 5238
Reputation: 85
try this
dataList= dataList.Select(x=>x.ChannelId=loopIndex++).ToList();
Upvotes: 0
Reputation: 45997
Here is a Linq
appraoch in one line without the requiremet to install another library
dataList = dataList.Select((x, i) => { x.ChannelId = i; return x; }).ToList();
Code: https://dotnetfiddle.net/SCEbyV
another appraoch - the classy for
loop way in one line
for (int i = 0; i < dataList.Count; i++) dataList[i].ChannelId = i;
Upvotes: 3
Reputation: 117154
If you NuGet Microsoft's "System.Interactive" extensions then you can do this:
dataList.ForEach((item, index) => item.ChannelId = index);
Upvotes: 6