此问题在此处已有答案:
Select multiple fields group by and sum(4个回答)
上个月关门了。
我有一个下面的列表,其中LineId
可以是相同的。在这种情况下,我想合并它们,它们是共同的。即,如果LineId
是相同的,然后总结Price
,Total
,AccountingTotal
和合并Description
文本。
我认为如果这个列表很大,我所做的方式不是最佳的。
- 我如何才能使这种性能有效?
- 什么是更好的方法来实现同样的结果?
{
"Lines": [
{
"Id": 1,
"AccountingTotal": 10.2,
"Description": "Description 1",
"Price": "10.00",
"Total": "10.00",
"LineId": "803"
},
{
"Id": 2,
"AccountingTotal": 10,
"Description": "Description 2",
"Price": "10.00",
"Total": "10.00",
"LineId": "804"
},
{
"Id": 3,
"AccountingTotal": 10.2,
"Description": "Description 3",
"Price": "10.00",
"Total": "10.00",
"LineId": "803"
}
]
}
字符串
期望列表:
{
"Lines": [
{
"Id": 1,
"AccountingTotal": 20.4,
"Description": "Description 1 | Description 3",
"Price": "20.00",
"Total": "20.00",
"LineId": "803"
},
{
"Id": 2,
"AccountingTotal": 10,
"Description": "Description 2",
"Price": "10.00",
"Total": "10.00",
"LineId": "804"
}
]
}
型
代码:
public class Line
{
public int Id { get; set; }
// This should be combination of id. i.e., "1|2|3", etc.
public string MergedId { get; set; }
public decimal? AccountingTotal { get; set; }
public string Description { get; set; }
public string Price { get; set; }
public string Total { get; set; }
public string LineId { get; set; }
}
// Data
var lines = new List<Line>
{
new Line
{
Id = 1,
AccountingTotal = (decimal?)10.2,
Description = "Description 1",
Price = "10.00",
Total = "10.00",
LineId = "803"
},
new Line
{
Id = 2,
AccountingTotal = (decimal?)10.2,
Description = "Description 2",
Price = "10.00",
Total = "10.00",
LineId = "804"
},
new Line
{
Id = 3,
Description = "Description 3",
Price = "10.00",
Total = "10.00",
LineId = "803"
}
};
var objNew = new List<Line>();
for (var i = 0; i < lines.Count; i++)
{
for (var j = i + 1; j < lines.Count; j++)
{
if (lines[i].LineId == lines[j].LineId)
{
lines[i].AccountingTotal += Math.Round(lines[i].AccountingTotal + lines[j].AccountingTotal, 2);
lines[i].Price = (Convert.ToDouble(lines[i].Price) + Convert.ToDouble(lines[j].Price)).ToString(CultureInfo.InvariantCulture);
lines[i].Total = (Convert.ToDouble(lines[i].Total) + Convert.ToDouble(lines[j].Total)).ToString(CultureInfo.InvariantCulture);
lines[i].Description += "|" + lines[j].Description;
}
}
objNew.Add(lines[i]);
}
// Pick first out of many dup ids
var result = objNew.GroupBy(x => x.LineId).Select(x => x.First()).ToList();
型
2条答案
按热度按时间ncecgwcz1#
合并是可能的.不那么复杂的方式。
如果你可以只通过LineId对“相似”的
Line
进行分组,那么在分组之后,你可以使用Aggregate
将组中每个Line
到第一个Line
的值相加:字符串
代码看起来很乱,因为你把十进制值存储为字符串,为了“安全”转换,我使用了
TryParse
。如果你把Price
和Total
改为decimal
或double
,甚至可以为空,代码会短得多。我的意思是,如果你允许更改属性类型,你可以将代码缩小到:
型
eit6fx6z2#
这里有一个方法,首先使用分组,然后根据您的需求进行“合并”:
字符串