2011-03-02 30 views
1

我有這樣LINQ - 依賴於對象類型檢索數據

public class ItemBase 
{ 
    public int ItemId { get; set; } 
    public DateTime Created { get; set; } 
    public ItemType Type { get; set; } 
} 

public class RockItem : ItemBase { } 

public class PlantItem : ItemBase 
{ 
    public bool IsDeadly { get; set; } 
} 

public class AnimalItemBase : ItemBase 
{ 
    public int NumberOfLegs { get; set; } 
    public bool IsDeadly { get; set; } 
} 

public class DogItem : AnimalItemBase { } 

public class CatItem : AnimalItemBase { } 

的結構有一個在數據庫中的一個類型標誌和我使用流利拆出上型,並返回一個IEnumerable<ItemBase>

這適用於我想要的大部分,但現在我處於需要將項目融合在一起的情況。例如,我想要在匿名對象中返回ItemIdIsDeadlyNumberOfLegs。結果必須在Created字段中的一個列表中排序。有沒有一種簡單的方法與linq做到這一點?理想情況下,我不需要將它們分開,合併結果,然後進行排序。

回答

1

你給的例子可以使用OfType解決:

IEnumerable<ItemBase> items = ... 
var results = items.OfType<AnimalItemBase>() 
        .OrderBy(x => x.Created).ToList(); 

如果您有支持跨類即具有IsDeadly財產所有項目的性質組合,你可以使用反射的組合檢查您要使用的屬性和dynamic以啓用您需要的duck typing,因爲從技術上講這些屬性是不同的IsDeadly屬性,您只需知道它們在您的方案中應該被視爲相同。

這樣做,您可以動態地分配您的匿名類型的屬性。即下面的示例返回的結果爲所有類型的有IsDeadly屬性:

var results = items.OrderBy(x => x.Created) 
        .Where(x => x.GetType().GetProperty("IsDeadly") !=null) 
        .Select(x => 
        { 
         dynamic o = x; 
         return new { IsDeadly = o.IsDeadly, Created = o.Created }; 
        }) 
        .ToList(); 

另外,作爲@Henk Holterman指出,它纔有意義返回匿名類型的枚舉,其中返回式品牌的每個屬性意義/定義爲全部枚舉中的項目。