2014-09-02 61 views
1

下面是類移調列表<T>使用C#

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(); 
+1

[關於與LINQ樞轉堆疊的問題](http://stackoverflow.com/questions/18238046/trying-to-pivot-data-using LINQ)嘗試搜索與LINQ的支點搜索 – RadioSpace 2014-09-02 23:02:13

+0

這可能有助於你http://stackoverflow.com/questions/320089/how-do-i-bind-a-wpf-datagrid-to-a-variable-number-列 – Seminda 2014-09-03 04:41:12

回答

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); 
} 
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); 
    } 
} 
+0

如果我不知道有多少種類型,即Type1,2,3,4..etc以及它們是什麼 – user3787610 2014-09-11 18:41:25

+0

@ user3787610我更新了答案。 – 2014-09-12 13:02:35