我有一个列表,如果LineId
是相同的,我将它们合并在一起.这一逻辑在所有情况下都适用,只有一种情况除外.在这里,这LineId
可以是""
或null
,如果是这样,我不想合并它.
当LineId
是""
或null
时,我怎么能不合并查询中的列表?
代码:
var groupedLines = lines
.GroupBy(line => line.LineId)
.Select(linesGroup => linesGroup.Aggregate((firstLine, nextLine) =>
{
// Logic is working as expected
return firstLine;
})).ToList();
我试着追随,但它仍然融合在一起
.GroupBy(line => !string.IsNullOrEmpty(line.LineId) )
示例1:(按预期工作)
输入
{
"Lines": [
{
"Id": "1",
"AccountingTotal": 10.2,
"Description": "Description 1",
"Price": "10.00",
"Total": "10.00",
"LineId": "101" <-- Merge because it is same
},
{
"Id": "2",
"AccountingTotal": 10,
"Description": "Description 2",
"Price": "10.00",
"Total": "10.00",
"LineId": "101" <-- Merge because it is same
}
]
}
输出
{
"Lines": [
{
"Id": "1|2",
"AccountingTotal": 20.2,
"Description": "Description 1|Description 1",
"Price": "20.00",
"Total": "20.00",
"LineId": "101"
}
]
}
示例2:(未按预期工作)
输入
{
"Lines": [
{
"Id": "1",
"AccountingTotal": 10.2,
"Description": "Description 1",
"Price": "10.00",
"Total": "10.00",
"LineId": "" <-- Do not merge if this is "" or null
},
{
"Id": "2",
"AccountingTotal": 10,
"Description": "Description 2",
"Price": "10.00",
"Total": "10.00",
"LineId": "" <-- Do not merge if this is "" or null
}
]
}
预期结果
{
"Lines": [
{
"Id": "1",
"AccountingTotal": 10.2,
"Description": "Description 1",
"Price": "10.00",
"Total": "10.00",
"LineId": ""
},
{
"Id": "2",
"AccountingTotal": 10,
"Description": "Description 2",
"Price": "10.00",
"Total": "10.00",
"LineId": ""
}
]
}
实际结果
{
"Lines": [
{
"Id": "1|2",
"AccountingTotal": 20.4,
"Description": "Description 1|Description 2",
"Price": "20.00",
"Total": "20.00",
"LineId": ""
}
]
}