我做了一個快速的控制檯應用程序作爲證明:
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<Record> input = new List<Record>();
input.Add(new Record { CheckNumber = 100, Step = "Book", Amount = 100 });
input.Add(new Record { CheckNumber = 100, Step = "Bank", Amount = 100 });
input.Add(new Record { CheckNumber = 100, Step = "Account", Amount = 100 });
input.Add(new Record { CheckNumber = 101, Step = "Book", Amount = 75 });
input.Add(new Record { CheckNumber = 101, Step = "Bank", Amount = 75 });
List<ExpandoObject> results = GetPivotRows(input);
//test
for (int i = 0; i < results.Count; i++)
{
dynamic record = results[i];
Console.WriteLine("{0} - {1} - {2} - {3}", record.CheckNumber, record.Book, record.Bank, record.Account);
}
}
public static List<ExpandoObject> GetPivotRows(List<Record> input)
{
List<string> steps = input.Select(e => e.Step).Distinct().ToList();
Dictionary<int, ExpandoObject> outputMap = new Dictionary<int,ExpandoObject>();
for (int i = 0; i < input.Count; i++)
{
dynamic row;
if(outputMap.ContainsKey(input[i].CheckNumber))
{
row = outputMap[input[i].CheckNumber];
}
else
{
row = new ExpandoObject();
row.CheckNumber = input[i].CheckNumber;
outputMap.Add(input[i].CheckNumber, row);
// Here we're initializing all the possible "Step" columns
for (int j = 0; j < steps.Count; j++)
{
(row as IDictionary<string, object>)[steps[j]] = new Nullable<int>();
}
}
(row as IDictionary<string, object>)[input[i].Step] = input[i].Amount;
}
return outputMap.Values.OrderBy(e => ((dynamic)e).CheckNumber).ToList();
}
}
public class Record
{
public int CheckNumber { get; set; }
public string Step { get; set; }
public decimal Amount { get; set; }
}
輸出:
100 - 100 - 100- 100
101 - 75 - 75 -
您可以使用反射來檢查的過程中產生的實際性能。
編輯:闡明這一點 - 如果我改變這種「測試」循環中的主要以:
for (int i = 0; i < results.Count; i++)
{
Console.WriteLine(string.Join(" - ", results[i]));
}
我得到:
[CheckNumber, 100] - [Book, 100] - [Bank, 100] - [Account, 100]
[CheckNumber, 101] - [Book, 75] - [Bank, 75] - [Account, ]
ExpandoObject
工具IDictionary<string, object>
幕後存儲無論它需要什麼,但同時實現IDynamicMetaObjectProvider
並與動態綁定一起工作。
你的意思是你想根據執行時間值動態地生成匿名類型屬性?不,那不行。您可以使用ExpandoObject,可能... –
初始值已經在LINQ列表中。我需要通過樞軸轉換它。我知道STEP的屬性在那裏,我只是不知道有多少,並且需要根據步驟 –
創建X個列。我必須做類似的事情。 [ExpandoObject](http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject(v = vs.110).aspx)如上所述是我發現的唯一方法。 – McAden