11

是否可以在 LINQ 中的 .Select 方法中跳过选择,例如 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
});
4

3 回答 3

5

您应该使用 aWhere过滤掉不需要的元素。这对于您当前的代码是不可能的,但是有很大的重构空间。像这样重写它:

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

如果“其他代码”也需要平台值,那么您应该首先投影到匿名类型:

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

一般来说,如果可能的话,你应该避免在这种 lambdas 中编写块表达式;块表达式会导致无法轻松组合的僵化代码。

于 2013-05-24T08:58:15.057 回答
2
var myFoos = from foo in allFoos
             let platform = LoadPlatform(foo)
             where platform != "BadPlatform"
             select LoadOwner(foo);
于 2013-05-24T08:38:09.297 回答
1

你可以这样做:

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
        });
于 2013-05-24T08:48:02.963 回答