是否可以在条件下取消选择和“继续”.Select语句?

时间:2013-05-24 08:33:49

标签: c# .net linq

是否可以在fore..each中跳过在LINQ-like'continue'中的.Select方法中选择?

var myFoos = allFoos.Select (foo =>                                                                                                 {

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

3 个答案:

答案 0 :(得分:3)

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

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

一般来说,如果可能的话,你应该避免在这种lambda中写块表达式;块表达式构成了无法轻松编写的严格代码。

答案 1 :(得分:2)

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

答案 2 :(得分: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
        });