pencilCake
pencilCake

Reputation: 53263

Is it possible to cancel select and 'Continue' within .Select statement upon a condition?

is it possible to skip selecting within .Select method in LINQ -like 'continue' in fore..each?

var myFoos = allFoos.Select (foo =>                                                                                                 {

    var platform = LoadPlatform(foo);
        if (platform == "BadPlatform") // TODO:  should skip and continue
        var owner = LoadOwner(foo);
        // .... Som eother loads
});

Upvotes: 12

Views: 9737

Answers (3)

Jon
Jon

Reputation: 437584

You should use a Where to filter out the elements you don't want. This is not possible with your current code, but there is lots of room for refactoring. Rewrite it like this:

var myFoos = allFoos
    .Where(foo => LoadPlatform(foo) != "BadPlatform")
    .Select(LoadOwner)
    // ...continue with your other code

If the "other code" also needs the platform value then you should project into an anonymous type first:

var myFoos = allFoos
    .Select(foo => new { Platform = LoadPlatform(foo), Foo = foo })
    .Where(o => o.Platform != "BadPlatform")
    .Select(o => new { Platform = o.Platform, Owner = LoadOwner(o.Foo), ... })
    // ...continue with your other code

In general you should avoid writing block expressions in this kind of lambdas if at all possible; block expressions make for rigid code that cannot be composed as easily.

Upvotes: 6

Ahmed KRAIEM
Ahmed KRAIEM

Reputation: 10427

You may do something like this:

var myFoos = allFoos
        .Select (foo => new {Platform = LoadPlatform(foo), Foo = foo})
        .Where(all => all.Platform != "BadPlatform")
        .Select(all => {
            var platform = all.Platform;//Not "BadPlatform"
            var owner = LoadOwner(all.Foo);
            // .... Som eother loads
        });

Upvotes: 1

Lee
Lee

Reputation: 144206

var myFoos = from foo in allFoos
             let platform = LoadPlatform(foo)
             where platform != "BadPlatform"
             select LoadOwner(foo);

Upvotes: 2

Related Questions