在你忽略或投票关闭这个问题之前,我认为这是一个值得提出的问题,因为代码清晰度是一个重要的讨论话题,它对编写可维护的代码至关重要,我非常希望那些曾经遇到过这个问题的人能够给出答案。
最近我遇到了这个问题,由于嵌套层数较多,LINQ查询很容易变得非常复杂。
以下是我为同一相对不复杂的查询所想出的格式差异的一些示例:
无格式
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格式,以最大化可读性和理解,并使其看起来整洁和专业。到目前为止,我无法决定,所以我把这个问题转给了这里的专业人士。