我的问题很难解决。我需要你的帮助这个问题。在codefirst中有很多关系。但我无法解决这个问题。我想使用Predicate func。但我无法解决它?如何使用“Method(Predicate func)”
public int Method<T>(Predicate<T> func)
{
var s1 = this.Uow.X.GetAll().Where(func)
.SelectMany(a => a.OrganizationalUnits.Where(q => Identity.Y.Contains(q.Z)))
.GroupBy(t => t, (k, g) => new
{
Tag = k,
Count = g.Count()
})
.OrderByDescending(g => g.Count);
var s2 = this.Uow.X.GetAll().Where(func)
.SelectMany(a => a.Classes.Where(q => Identity.Y.Contains(q.K)))
.GroupBy(t => t, (k, g) => new
{
Tag = k,
Count = g.Count()
})
.OrderByDescending(g => g.Count);
var s3 = this.Uow.X.GetAll().Where(func)
.SelectMany(a => a.Courses.Where(q => Identity.Y.Contains(q.L)))
.GroupBy(t => t, (k, g) => new
{
Tag = k,
Count = g.Count()
})
.OrderByDescending(g => g.Count);
return s1.ToString().Count() + s2.ToString().Count() + s3.ToString().Count();
}
答案 0 :(得分:1)
这是做到这一点的方法。我还删除了最后一行的ToString()
,因为您不需要将对象作为字符串来计算它。
这样打电话:int result = Method<TypeGoesHere>(p => p == aValue);
public int Method<T>(Expression<Func<T, Boolean>> Predicate)
{
var s1 = this.Uow.X.GetAll().Where(Predicate)
.SelectMany(a => a.OrganizationalUnits.Where(q => Identity.Y.Contains(q.Z)))
.GroupBy(t => t, (k, g) => new
{
Tag = k,
Count = g.Count()
})
.OrderByDescending(g => g.Count);
var s2 = this.Uow.X.GetAll().Where(Predicate)
.SelectMany(a => a.Classes.Where(q => Identity.Y.Contains(q.K)))
.GroupBy(t => t, (k, g) => new
{
Tag = k,
Count = g.Count()
})
.OrderByDescending(g => g.Count);
var s3 = this.Uow.X.GetAll().Where(Predicate)
.SelectMany(a => a.Courses.Where(q => Identity.Y.Contains(q.L)))
.GroupBy(t => t, (k, g) => new
{
Tag = k,
Count = g.Count()
})
.OrderByDescending(g => g.Count);
return s1.Count() + s2.Count() + s3.Count();
}
我认为你可能想要一个this
类型的扩展方法。它看起来像这样(如果thisType
是this
的类型)。这不需要是模板,因为您(但不是我)知道X.GetAll()
的类型。我猜测列表<int>
会产生T int。我还将代码更改为更简洁,但具有相同的功能。 (这可能是你原来的代码做错了,但这也是做同样的事情。)
这样打电话:
thisType something = new something();
someType aValue = X; // don't know the type here.
// do stuff with something
int result = something.Method(p => p == aValue);
代码:
public static int Method(this thisType me, Expression<Func<someType, Boolean>> Predicate)
{
var allOfEm = me.Uow.X.GetAll().Where(Predicate);
var s1 = allOfEm
.SelectMany(a => a.OrganizationalUnits.Where(q => Identity.Y.Contains(q.Z)))
.Distinct();
var s2 = allOfEm
.SelectMany(a => a.Classes.Where(q => Identity.Y.Contains(q.K)))
.Distinct();
var s3 = allOfEm
.SelectMany(a => a.Courses.Where(q => Identity.Y.Contains(q.L)))
.Distinct();
return s1.Count() + s2.Count() + s3.Count();
}