开发者

linq - retrieving data dependent on the object type

I have a structure like this

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 { }

There is a type flag in the database and I use Fluent to split out on type and return an IEnumerable<ItemBase>

This works for most of what I want, but now I am in a situation where I need to meld the items together. For instance, I want the ItemId, IsDeadly, and the NumberOfLegs returned in an anonymous object. The results have to be sorted on the Created field in one list. Is 开发者_开发技巧there an easy way to do this with linq? Ideally, I would not have to split these out, merge the results, and then sort.


The example you give could be solved using OfType:

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

If you have to support combinations of properties that cross classes i.e all items that have the IsDeadly property, you could use a combination of reflection to check the properties you want to use and dynamic to enable the duck typing you need, since technically these are different IsDeadly properties, you just know they should be treated the same in your scenario.

Doing that you can then assign the properties in your anonymous type dynamically. I.e. the following example returns results for all of your types that have the IsDeadly property:

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

Also as @Henk Holterman pointed out, it only makes sense to return an enumeration of anonymous types where each property of the returned type makes sense / is defined for all the items in the enumeration.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜