格式化LINQ查询的最佳方法 [英] Best ways to format LINQ queries

查看:118
本文介绍了格式化LINQ查询的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在忽略/投票关闭该问题之前,我认为这是一个有效的问题,因为代码清晰性是重要的讨论主题,编写可维护的代码,我将不胜感激以前遇到过这些问题的人的答案.

Before you ignore / vote-to-close this question, I consider this a valid question to ask because code clarity is an important topic of discussion, it's essential to writing maintainable code and I would greatly appreciate answers from those who have come across this before.

我最近遇到了这个问题,由于大量的嵌套,LINQ查询很快就会变得非常讨厌.

I've recently run into this problem, LINQ queries can get pretty nasty real quick because of the large amount of nesting.

下面是一些示例,这些示例说明了我提出的格式差异(对于相同的相对非复杂的查询)

Below are some examples of the differences in formatting that I've come up with (for the same relatively non-complex query)

无格式

var allInventory = system.InventorySources.Select(src => new { Inventory = src.Value.GetInventory(product.OriginalProductId, true), Region = src.Value.Region }).GroupBy(i => i.Region, i => i.Inventory);

高格式

var allInventory = system.InventorySources
    .Select(src => 
        new { 
            Inventory = src.Value.GetInventory(product.OriginalProductId, true), 
            Region = src.Value.Region })
                .GroupBy(
                    i => i.Region, 
                    i => i.Inventory);

块格式

var allInventory = system.InventorySources
    .Select(
        src => new 
        { 
            Inventory = src.Value.GetInventory(product.OriginalProductId, true), 
            Region = src.Value.Region 
        })
        .GroupBy(
            i => i.Region, 
            i => i.Inventory
        );

列表格式

var allInventory = system.InventorySources
    .Select(src => new { Inventory = src.Value.GetInventory(product.OriginalProductId, true), Region = src.Value.Region })
    .GroupBy(i => i.Region, i => i.Inventory);

我想提出一个linq格式的标准,以便最大程度地提高可读性&理解,看起来干净专业.到目前为止,我还无法决定,所以我将问题转给这里的专业人员.

I want to come up with a standard for linq formatting so that it maximizes readability & understanding and looks clean and professional. So far I can't decide so I turn the question to the professionals here.

推荐答案

我已经决定使用块格式了.它困扰了我一段时间的浪费空间"感,但最终每个人都觉得更多的人更容易理解.由于我们已经在新行上添加了大括号,因此它与其余的代码更加匹配.解释的空间也较小.我们在公共商店中保存有一个带有格式示例的cs文件...当有人提出一个独特的linq块时,我们将其添加到文件中...确实对新手有所帮助.

I have settled on Block formatting. It bothered my sense of "wasted space" for a while but ultimately everyone felt it was more readable by more people. As we were already putting braces on new lines it just fit better with the rest of the code. There is also less room for interpretation. We keep a cs file in the public store that has formatting examples...when somebody comes up with a unique hunk of linq we add it to the file...really helps the new guys.

这篇关于格式化LINQ查询的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆