我有5个不同的数据源(请求,lsitCC, listSEDI, listSEDIFees和XMLRoot加载到各自的c#数组列表对象)。我需要根据某些条件组合来自所有这些源的数据来构造一个JSON请求。我在c#中使用NewtonSoft.JSON编写了以下代码。这个LINQ查询的圈复杂度大约在40左右,这是一个较高的边。谁能就如何降低复杂性提出建议?提前感谢。我认为查询是相当用户可读的,请让我知道如果内联注释是必需的。
var input = from RequestNode in request
select new
{
Documents = (from objCC in lsitCC
where objCC.ID == RequestNode.ID
select new
{
Request = (from objSEDI in listSEDI
where objSEDI.ID == objCC.ID && RequestNode.POSTAL.Count(p => p.PID == objSEDI.PID) > 0
join Config in RequestNode.POSTAL on objSEDI.PID equals Config.PID
select new
{
ReqItem = (Config.ReqItem == null) ? "" : Config.ReqItem,
Code = (RequestNode.Code == null) ? "" : RequestNode.Code,
Camp = (RequestNode.Camp == null) ? "" : RequestNode.Camp,
CCT = new
{
ID = (objCC.ID == null) ? "" : objCC.ID,
Band = (RequestNode.Band == null) ? "" : RequestNode.Band,
Context = (RequestNode.Context == null) ? 0 : RequestNode.Context,
IsActive = (RequestNode.IsActive == null) ? false : RequestNode.IsActive,
MaxLimit = (objCC.MaxLimit == null) ? 0 : objCC.MaxLimit,
MinLimit = (objCC.MinLimit == null) ? 0 : objCC.MinLimit
},
User = RequestNode.User,
POSTAL = new
{
PID = (objSEDI.PID == null) ? "" : objSEDI.PID,
Type = (Config.Type == null) ? "" : Config.Type,
Amount = (Config.Amount == null) ? 0 : Config.Amount,
IsValid = (Config.IsValid == null) ? false : Config.IsValid,
Code = (Config.Code == null) ? "" : Config.Code,
Infos = new
{
Info = (from objRoot in XMLRoot
where objRoot.ID == objCC.ID && objRoot.Channel == "Channel1" && objRoot.Group == "GROUP_1" && objRoot.Code == Config.Type.Substring(0, 3) && objRoot.PIDCode == Config.Type.Substring(3, 1)
select new
{
InfoFrom = (objRoot.InfoFrom == null) ? "" : objRoot.InfoFrom,
Selection = (objRoot.Handling == null) ? "" : objRoot.Selection,
Rate = (objRoot.Rate == null) ? "" : objRoot.Rate
})
},
POSTALFee = from objSEDIFee in listSEDIFees
where objSEDIFee.ID == objCC.ID && objSEDIFee.PID == objSEDI.PID
select new
{
BaseValue = (objSEDIFee.BaseValue == null) ? 0 : objSEDIFee.BaseValue,
UpdatedValue = (objSEDIFee.UpdatedValue == null) ? 0 : objSEDIFee.UpdatedValue,
BaseType = (objSEDIFee.BaseType == null) ? "" : objSEDIFee.BaseType,
UpdatedType = (objSEDIFee.UpdatedType == null) ? 0 : objSEDIFee.UpdatedType
},
OutputRoot = new
{
Output = from output in outputroot
select new
{
Type = 0,
SubType = 0,
OutputReference = 0
}
}
},
})
})
};
var streamRead = JsonConvert.SerializeObject(input, Newtonsoft.Json.Formatting.Indented);
这似乎只是在代码库中添加适当数量的翻译器的情况。是的,翻译是乏味的,但如果你觉得你在一个查询中有太多的逻辑,我建议你可以这样做。
这将意味着你必须要么放弃匿名类型,要么接受动态关键字(这甚至可以吗?!)
您可能还需要查看某种构建模式或中间状态。
进一步检查,您似乎在查询的中间引入了一些全局变量,例如XMLRoot
&listSEDIFees
。如果表述得更明确一些可能会更好。您还可以通过使用where子句的静态部分(objRoot.Channel == "Channel1" && objRoot.Group == "GROUP_1"
)预先过滤XMLRoot
来减少过多的工作,而不是每次都重新运行它。比如
var channel1Group1Info = XMLRoot.Where(objRoot=>objRoot.Channel == "Channel1" && objRoot.Group == "GROUP_1").ToArray();