以下是课程
public class ErrorDTO
{
public string Type { get; set; }
public string Data { get; set; }
}
我有ErrorDTO列表,即List<ErrorDTO>
以下是数据
Type1 x
Type1 y
Type2 z
Type3 p
Type2 q
依旧......
我想以下列方式在xaml的DataGrid中显示它
Type1 Type2 Type3
x z p
y q
我该怎么做?我尝试将列表转换为数据表,但没有运气。
invalidDataList是List<ErrorDTO>
var r = invalidDataList
.Distinct()
.GroupBy(x => x.Type)
.Select(y => new { Type = y.Key, Data = y });
DataTable table = new DataTable();
foreach (var item in r)
{
table.Columns.Add(item.Type, typeof(string));
foreach (var i in item.Data)
{
DataRow dr = table.NewRow();
dr[item.Type] = i.Data;
table.Rows.Add(dr);
}
}
dataGrid.ItemsSource = table.AsEnumerable();
答案 0 :(得分:2)
以下代码可以帮助您:
lst.GroupBy (l => l.Type).Select (l => new {
Type1 = l.Where (x => x.Type == "Type1").Select (x => x.Data),
Type2 = l.Where (x => x.Type == "Type2").Select (x => x.Data),
Type3 = l.Where (x => x.Type == "Type3").Select (x => x.Data)
});
对于数据透视表,如果您不知道列表中有多少类型,我认为最简单的解决方案是先检查lst
列表中的不同类型:
var types = lst.Select (l => l.Type).Distinct().OrderBy (l => l).ToList();
然后使用DataTable:
var dt = new DataTable("Test");
DataRow workRow;
for (int i = 0; i < types.Count; i++)
{
dt.Columns.Add(types[i]);
var dataToInsert = lst.Where (l => l.Type == types[i]).Select (l => l.Data).ToList();
foreach (var element in dataToInsert)
{
workRow = dt.NewRow();
workRow[types[i]] = element;
dt.Rows.Add(workRow);
}
}
答案 1 :(得分:0)
var typed = invalidDataList
.GroupBy(d => d.Type)
.Select(g => new
{
Type = g.Key,
Data = g.Select(d => d.Data).ToList()
})
.ToList();
var table = new DataTable();
foreach(var type In typed)
{
table.Columns.Add(type.Type);
}
var maxCount = typed.Max(t => t.Data.Count);
for(var i = 0; i < maxCount; i++)
{
var row = table.NewRow();
foreach(var type in typed)
{
if (type.Data.Count > i)
{
row[type.Type] = type.Data[i]
}
}
table.Rows.Add(row);
}