我有一个 channel 列表,我的一些 channel 有未分配的单元,然后将这些单元传递到一个单独的容器中。我真正想做的是将 ForEach 调用中列表当前位置的索引传递到我的容器中。我可以用 linq 做这样的事情还是我最好改用 for..loop?
如果可能的话,我很乐意使用 linq :) 无论如何,这是我的代码:
item.Channels.Where(ch => !ch.IsSkipped).ForEach(
ch =>
{
if (ch.AssignedUnit == null)
{
//unknownUnitChannels.Add(ch);
unknownUnitChannels.Add(index, ch) <== This is the index i'd like to pass there
}
});
最佳答案
如果你想使用原始索引(在应用 Where
之前),你需要像这样的东西:
item.Channels.Select((c, i) => new { Channel = c, Index = i })
.Where(x => !x.Channel.IsSkipped)
.ForEach(x =>
/* x.Channel is your item, x.Index is its original Index */
);
关于c# - 获取 ForEach 中的当前索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27403899/