我需要按列分組,并連接 1 列,并對 1 列進行求和。
分組方式:第一個按供應商,然后按型別
連接方式:月
總和:NumberInvoice
這是我的代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var InputData = new List<Invoice>()
{
new Invoice{ Vendor = "Microsoft", NumberInvoice= 10, Type= "PC", Month = "1" },
new Invoice{ Vendor = "Microsoft", NumberInvoice= 10, Type= "PC", Month = "2" },
new Invoice{ Vendor = "Microsoft", NumberInvoice= 10, Type= "Surface", Month = "1" },
new Invoice{ Vendor = "Microsoft", NumberInvoice= 20, Type= "PC", Month = "1" },
new Invoice{ Vendor = "Microsoft", NumberInvoice= 20, Type= "PC", Month = "2" },
new Invoice{ Vendor = "Microsoft", NumberInvoice= 30, Type= "Surface", Month = "1" },
new Invoice{ Vendor = "IBM", NumberInvoice= 50, Type= "Network", Month = "5" },
new Invoice{ Vendor = "IBM", NumberInvoice= 60, Type= "Graphic Card", Month = "6" }
};
var result = (InputData.AsEnumerable() ?? throw new InvalidOperationException()).Select(
x => new
{
x.Vendor,
x.NumberInvoice,
x.Type,
x.Month
}
).GroupBy(
y => new
{
y.Vendor,
y.NumberInvoice,
y.Type,
y.Month
}
)
.Select(
a => new Invoice
{
Vendor = a.Key.Vendor,
NumberInvoice = a.Key.NumberInvoice,
Type = a.Key.Type,
Month = a.Key.Month,
}
).ToList();
foreach (var item in result)
{
Console.WriteLine(item.Vendor " " item.NumberInvoice " " item.Type " " item.Month);
}
Console.ReadKey();
}
public class Invoice
{
public string Vendor { get; set; }
public decimal NumberInvoice { get; set; }
public string Type { get; set; }
public string Month { get; set; }
}
}
}
這是輸出
Microsoft 10 PC 1
Microsoft 10 PC 2
Microsoft 10 Surface 1
Microsoft 20 PC 1
Microsoft 20 PC 2
Microsoft 30 Surface 1
IBM 50 Network 5
IBM 60 Graphic Card 6
所需的輸出應該是這樣的:
Vendor Type Month NumberInvoice
-------------------------------------------------
Microsoft PC 1,2 60
Microsoft Surface 1 40
IBM Network 5 50
IBM Graphic Card 6 60
如您所見,對于 Microsoft,第 1 個月和第 2 個月連接在一起,并對 NumberInvoice 進行求和。所以我可以完成這個輸出嗎?
uj5u.com熱心網友回復:
你應該
Vendor只分組Type。為.
.Sum()_NumberInvoice對于Months,.Select()和.Distinct()將不同的月份添加到串列中。將結果回傳為
List<GroupedInvoice>。(創建另一個類以將其保存Months為string串列/陣列。(可選)第一個
.Select()對我來說是不必要的,建議被洗掉。
var result = (InputData.AsEnumerable() ?? throw new InvalidOperationException())
.GroupBy(
y => new
{
y.Vendor,
y.Type
}
)
.Select(
a => new GroupedInvoice
{
Vendor = a.Key.Vendor,
Type = a.Key.Type,
NumberInvoice = a.Sum(x => x.NumberInvoice),
Month = a.Select(x => x.Month).Distinct().ToArray(),
}
).ToList();
public class GroupedInvoice
{
public string Vendor { get; set; }
public decimal NumberInvoice { get; set; }
public string Type { get; set; }
public string[] Months { get; set; }
}
演示@.NET Fiddle
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/526954.html
