2017-04-22 130 views
0

顯示數據說我有兩種不同的模式:如何從兩個模型在一個表中基於共同的屬性

public class ModelA 
{ 
    public int  Id   { get; set; } 
    public DateTime Date  { get; set; } 
    public string Attribute1 { get; set; } 
} 

public class ModelB 
{ 
    public int  Id   { get; set; } 
    public DateTime Date  { get; set; } 
    public string Attribute2 { get; set; } 
    public string Attribute3 { get; set; } 
} 

我想在同一個表中的單個視圖來顯示這一點。模型大多不相關。我想忽略的ID在該表中,但顯示按日期排序的項目以這樣的方式:

| Date  | Attribute1 | Attribute2 | Attribute3 | 
| 2008-01-01 | null  | value  | value  | (ModelB item) 
| 2009-01-01 | value  | null  | null  | (ModelA item) 
| 2010-01-01 | value  | null  | null  | (ModelA item) 
| 2011-01-01 | null  | value  | value  | (ModelB item) 

爲清楚:我不希望通過在表,其中有空白點,顯示比其他的區別其中一個單元沒有數據。

加入數據集不起作用,因爲沒有要加入的值(我希望顯示所有日期),它更多是我想要加入的列。

我該怎麼做到這一點?

+0

目前尚不清楚你的要求,但它相當於SQL的' UNION'操作? – sergiol

+0

它確實是一個聯合操作符,並具有創建新對象所需的額外步驟,以便能夠這樣做,如接受的答案中所示。 – deemzet

回答

0

您可以聯合他們,這樣的事情你應該做的

list1.Select(x => new { 
          Id   = x.Id, 
          Date  = x.Date, 
          Attribute1 = x.Attribute1, 
          Attribute2 = null, 
          Attribute3 = null 
         } 
      ).Union(list2.Select(x => new { 
          Id   = x.Id, 
          Date  = x.Date, 
          Attribute1 = null, 
          Attribute2 = x.Attribute2, 
          Attribute3 = x.Attribute3 
        })); 

,做你的工作在聯盟榜首

+0

我最終創建了一個新類來捕獲這個無名稱的對象,並在我看來用它。完美工作! – deemzet

相關問題