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 { }
数据库中有一个类型标志,我使用 Fluent 来拆分类型并返回 IEnumerable
这适用于我想要的大部分内容,但现在我是在我需要将这些项目融合在一起的情况下。例如,我希望在匿名对象中返回 ItemId
、IsDeadly
和 NumberOfLegs
。结果必须按一个列表中的 Created
字段进行排序。有没有一种简单的方法可以用 linq 来做到这一点?理想情况下,我不必将它们分开,合并结果,然后排序。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您给出的示例可以使用
OfType
来解决:如果您必须支持跨类的属性组合,即所有具有
IsDeadly
属性的项目,您可以使用以下组合反射检查您要使用的属性,动态
启用鸭子打字 您需要,因为从技术上讲,这些是不同的IsDeadly
属性,您只需知道在您的场景中应该对它们进行相同的处理。这样做之后,您就可以动态分配匿名类型中的属性。即,以下示例返回具有 IsDeadly 属性的所有类型的结果:
另外,正如 @Henk Holterman 指出的那样,只有返回匿名类型的枚举才有意义,其中返回类型的每个属性有意义 / 是为枚举中的所有项目定义的。
The example you give could be solved using
OfType
: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 anddynamic
to enable the duck typing you need, since technically these are differentIsDeadly
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: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.