If you compile to a Func<User, int>
, you can call it in other areas like so:
Expression<Func<User, int>> userExpression = x => x.Roles.Count();
Func<User,int> userFunc = userExpression.Compile();
users.Select(x => new AnotherClass { RoleCount = userFunc(x) });
Or simply define as a Func
to begin with:
Func<User,int> userFunc = x => x.Roles.Count();
Is this using Linq-to-Objects or something else? If you need to keep it as an Expression
because the Expression
gets converted into something else (like a SQL call), you can use LinqKit's AsExpandable
like so:
public static Expression<Func<User,int>> RoleCount()
{
return u => u.Roles.Count();
}
public static void DoStuff()
{
var roleCounter = RoleCount();
var query = users.AsExpandable()
.Select(u => roleCounter.Invoke(u));
}