globetrotter
globetrotter

Reputation: 1047

Access item in sequence that was skipped using LINQ's .Skip()

foreach(var item in items.Where(x => x.SomeCondition == true).Skip(1))
{
    item.OneThing = true;
    item.AnotherThing = true;
}

For the item that was skipped using .Skip(1), I also need to set .AnotherThing to true. I can iterate everything without .Skip(1) and set .AnotherThing to true, then iterate everything with .Skip(1) and set .OneThing to true. Is there a more elegant way to do this, rather than looping through the collection twice?

Edit: What if there was a .YetAnotherThing property, which needed to be set on the item that was skipped using .Skip(1)?

Upvotes: 1

Views: 423

Answers (3)

krillgar
krillgar

Reputation: 12805

Don't use Skip(1) in your foreach loop then. You can also do a Select to get the index as the second parameter.

foreach (var item in items.Where(x => x.SomeCondition)
                          .Select((x, i) => new { item = x, index = i })
{
    // If you have a lot to do:
    if (item.index != 0)
    {
        item.item.YetAnotherThing = 15;
        item.item.OneThing = true;
    }

    // If you have a simple boolean
    item.item.OneThing = item.index != 0;

    // Something that will always happen.
    item.item.AnotherThing = true;
}

Granted, in actual code, please pick better variable names than what would create item.item.

Upvotes: 1

Liu
Liu

Reputation: 982

How about

var newItems = items.Where(x => x.SomeCondition == true).ToList();
if(newItems.Count != 0)
{
    newItems.ForEach(i => i.AnotherThing = true);
    newItems.FirstOrDefault().OneThing = true;
}

Upvotes: -1

Jon Skeet
Jon Skeet

Reputation: 1500555

Well it sounds like you don't want to use Skip in this case. Just use a local variable to remember whether this is the first iteration or not.

bool firstItem = true;
foreach(var item in items.Where(x => x.SomeCondition))
{
    item.AnotherThing = true;
    if (!firstItem)
    {
        item.OneThing = true;
    }
    firstItem = false;
}

Upvotes: 4

Related Questions