I have a method that currently accepts Func<Product, string>as a parameter, but I need it to be Expression<Func<Product, string>>. Using AdventureWorks, here is an example of what I would like to do using Func.
private static void DoSomethingWithFunc(Func<Product, string> myFunc)
{
using (AdventureWorksDataContext db = new AdventureWorksDataContext())
{
var result = db.Products.GroupBy(product => new
{
SubCategoryName = myFunc(product),
ProductNumber = product.ProductNumber
});
}
}
I would like it to look something like this:
private static void DoSomethingWithExpression(Expression<Func<Product, string>> myExpression)
{
using (AdventureWorksDataContext db = new AdventureWorksDataContext())
{
var result = db.Products.GroupBy(product => new
{
SubCategoryName = myExpression(product),
ProductNumber = product.ProductNumber
});
}
}
However, the problem that I ran into is that it is myExpression(product)invalid (will not compile). After reading some other posts, I understand why. And if it weren’t for the fact that I need a variable productfor the second part of my key, I could probably say something like this:
var result = db.Products.GroupBy(myExpression);
product, (ProductNumber). , . Func, . , , , product. ?
EDIT: , :
DoSomethingWithFunc(product => product.ProductSubcategory.Name);