在实体框架中,我有一个主类,其中包含两个子类的ICollection定义。
public partial class Class1{
public virtual ICollection<Class2> Class2 {get;set;}
public virtual ICollection<Class3> Class3 {get;set;}
}
public partial class Class2 : ITotal {
public double Total {get;}
}
public partial class Class3 {
}Class2实现了ITotal interface...Class3没有实现的功能。
总的来说,Class1有大约30个ICollections实例,其中基本对象实现了ITotal接口。它还有不实现接口的10+ ICollections。
在Class1中,我需要能够动态地获取其基本类型实现ITotal接口的所有ICollections。然后,我将添加“总计”字段,以获得一个总体总数。我之所以需要它是动态的,是因为我将向class1中添加更多的class1,并且我不想/不需要记住去多个地方才能得到精确的总数。
下面是我所拥有的示例,所以far...this代码为我提供了所有的ICollection类,但是现在我被困住了。理想情况下,我可以在最后一个选择之后添加另一个where子句,但我愿意完全取消它。
var value1 = t.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
.Where(x => x.CanWrite && x.GetGetMethod().IsVirtual)
.Select(x => x.GetValue(this, null))
.Where(x => x != null)
.Where(x => x.GetType().GetInterfaces().Any(y => y.IsGenericType && y.GetGenericTypeDefinition() == typeof(ICollection<>)))
.Select(x=> ((IEnumerable)x))
.ToList()
;有什么想法吗?
发布于 2017-09-11 14:15:43
如下所示:
var c = new Class1();
//. . .
var q = from p in typeof(Class1).GetProperties()
where p.PropertyType.IsConstructedGenericType
&& p.PropertyType.GetGenericTypeDefinition().Equals(typeof(ICollection<>))
&& typeof(ITotal).IsAssignableFrom(p.PropertyType.GetGenericArguments()[0])
select p;
var ITotalCollections = q.ToList();
var q2 = from p in ITotalCollections
from i in (IEnumerable<ITotal>)p.GetValue(c)
select i.Total;
var total = q2.Sum();https://stackoverflow.com/questions/46156654
复制相似问题