Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

linq

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
});
like image 356
pencilCake Avatar asked May 24 '13 08:05

pencilCake


3 Answers

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.

like image 159
Jon Avatar answered Dec 06 '22 14:12

Jon


var myFoos = from foo in allFoos
             let platform = LoadPlatform(foo)
             where platform != "BadPlatform"
             select LoadOwner(foo);
like image 26
Lee Avatar answered Dec 06 '22 14:12

Lee


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
        });
like image 27
Ahmed KRAIEM Avatar answered Dec 06 '22 15:12

Ahmed KRAIEM