Ankit K
Ankit K

Reputation: 1326

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=...)

Suggestions please.

Upvotes: 1

Views: 5238

Answers (4)

Yakamuz
Yakamuz

Reputation: 85

try this

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

Upvotes: 0

fubo
fubo

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

Mahfuz Morshed
Mahfuz Morshed

Reputation: 118

try this

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

Upvotes: 3

Enigmativity
Enigmativity

Reputation: 117154

If you NuGet Microsoft's "System.Interactive" extensions then you can do this:

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

Upvotes: 6

Related Questions