2 回答

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超6個(gè)贊
GroupBy您可以通過(guò)使用and來(lái)實(shí)現(xiàn)這一點(diǎn)ExpandoObject:
var result = new List<ExpandoObject>();
foreach (var orders in orderList.GroupBy(obj => obj.ProductID))
{
var record = new ExpandoObject();
foreach (var order in orders.AsEnumerable())
{
((IDictionary<string, object>)record).Add(order.Date, order.Amount);
}
result.Add(record);
}

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超9個(gè)贊
你想要一個(gè)像 excel 一樣的數(shù)據(jù)透視表。下面的代碼創(chuàng)建了兩個(gè)數(shù)據(jù)表。您列出的第一個(gè)基礎(chǔ)。然后它需要第一個(gè)表并創(chuàng)建第二個(gè)數(shù)據(jù)透視表
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication93
{
class Program
{
static void Main(string[] args)
{
Order order = new Order();
DataTable dt = order.MakeTable();
//now create piviot table
string[] dates = dt.AsEnumerable().Select(x => x.Field<string>("Date")).Distinct().ToArray();
DataTable pivot = new DataTable();
pivot.Columns.Add("ProductID", typeof(string));
foreach (string date in dates)
{
pivot.Columns.Add(date, typeof(int));
}
var groups = dt.AsEnumerable().GroupBy(x => x.Field<string>("ProductID")).ToList();
foreach(var group in groups)
{
DataRow newRow = pivot.Rows.Add();
newRow["ProductID"] = group.Key;
foreach (var col in group)
{
newRow[col.Field<string>("Date")] = col.Field<int>("Amount");
}
}
}
}
internal class Order
{
public Order()
{
}
public string ProductID { get; set; }
public int Amount { get; set; }
public string Date { get; set; }
public DataTable MakeTable()
{
DataTable dt = new DataTable();
List<Order> orderList = new List<Order>() {
new Order(){ ProductID="12345", Amount=300, Date = "2018-12-19"},
new Order(){ ProductID="12345", Amount=0, Date = "2018-12-20"},
new Order(){ ProductID="12345", Amount=200, Date = "2018-12-21"},
new Order(){ ProductID="12345", Amount=250, Date = "2018-12-22"},
new Order(){ ProductID="12345", Amount=30, Date = "2018-12-23"},
new Order(){ ProductID="67898", Amount=20, Date = "2018-12-20"},
new Order(){ ProductID="67898", Amount=30, Date = "2018-12-21"},
new Order(){ ProductID="67898", Amount=40, Date = "2018-12-22"},
new Order(){ ProductID="67898", Amount=50, Date = "2018-12-23"},
new Order(){ ProductID="67898", Amount=130, Date = "2018-12-24"}
};
foreach (var prop in this.GetType().GetProperties())
{
string typeName = prop.PropertyType.FullName;
Type systemType = System.Type.GetType(typeName);
dt.Columns.Add(prop.Name, systemType);
}
foreach (Order row in orderList)
{
object[] data = row.GetType().GetProperties().Select(x => x.GetValue(row, null)).ToArray();
dt.Rows.Add(data);
}
return dt;
}
}
}
- 2 回答
- 0 關(guān)注
- 173 瀏覽
添加回答
舉報(bào)