代码清理:在多行上拆分长语句的最佳方法

rya*_*uyu 1 c# linq indentation code-cleanup

我有一个相当长的逻辑陈述,它需要分成多行.打破声明的最佳位置在哪里?是否存在拆分逻辑操作数和linq lambda表达式的约定?带有ReSharper的Visual Studio 2013以这种方式格式化语句:

var b =
    wmsDocument.Document.Types.All(
        typePair => validTypes.Any(type => type.DocumentTypeId == typePair.DocumentTypeId &&
                                            (String.IsNullOrWhiteSpace(typePair.DocumentSubTypeId) ||
                                                (type.SubTypes != null &&
                                                type.SubTypes.Any(
                                                    subType =>
                                                        subType.DocumentSubTypeId == typePair.DocumentSubTypeId)))));
Run Code Online (Sandbox Code Playgroud)

我知道我可以通过一些方法调用来分解逻辑,但我真的想知道是否有人有关于如何缩进这些类型语句的约定.到目前为止,我还没有在网上找到任何运气.

Pio*_*ski 6

很难说这个问题有一个很好的答案。这真的是一个品味问题。就个人而言,我喜欢在点上打破 LINQ 查询。

var result = data
               .Where(a => a == someValue)
               .Take(5)
               .ToList();
Run Code Online (Sandbox Code Playgroud)

另外,我更喜欢将每个条件放在单独的行中:

if (a == b ||
    b == c ||
    c == a)
{

}
Run Code Online (Sandbox Code Playgroud)

将这两个首选项应用于您的查询,我得到了类似的结果:

var b =
    wmsDocument.Document.Types
    .All(typePair => validTypes
        .Any(type => type.DocumentTypeId == typePair.DocumentTypeId && 
            (String.IsNullOrWhiteSpace(typePair.DocumentSubTypeId) ||
            (type.SubTypes != null && 
            type.SubTypes
                .Any(subType => subType.DocumentSubTypeId == typePair.DocumentSubTypeId)))));
Run Code Online (Sandbox Code Playgroud)


Tra*_*s J 6

有多种方法可以做到这一点.这取决于您在紧凑和可读之间绘制线的位置.这将是可读的一面,虽然略微详细确实至少允许嵌套的linq表达式中的注释.

//determine if every document type
var b = wmsDocument.Document.Types.All
(
    //contains at least one typePair
    typePair => validTypes.Any
    (
        //where the type's id and the typePair's id are equal
        type => type.DocumentTypeId == typePair.DocumentTypeId && 
        (
            //and the subtype's id has a value
            String.IsNullOrWhiteSpace(typePair.DocumentSubTypeId) || 
            (
                //or the subtype collection is populated and contains a matching subtypeid
                type.SubTypes != null && type.SubTypes.Any
                (
                    subType => subType.DocumentSubTypeId == typePair.DocumentSubTypeId
                )
            )
        )
     )
);
Run Code Online (Sandbox Code Playgroud)