简体   繁体   中英

How would I use an anonymous result type for an expression delegate for LINQ to SQL?

I have an existing LINQ to SQL query, where I'm trying to allow for different groupings:

var result= dc.Report_Data
                .Where(x => x.Year == Year)
                .Where(x => x.Month >= Month)
                .GroupBy(grouping)
                .Select(g => new ReportViewModel(){
                    Month = g.Key.Month,
                    Option1 = g.Key.Option1, 
                    Option2 = g.Key.Option2,
                    Amount = g.Sum(x => x.Amount)
                })
                .ToList();

I need to allow a different sets of properties to group by, based on an external parameter. I set a default value, then use conditionals like this:

Expression<Func<Report_Data, TResult>> grouping = g => new {g.Month, Option1 = g.prop1, Option2 = g.prop2};

if (userParameter == "X"){
    grouping = g => new {g.Month, Option1 = g.prop3, Option2 = g.prop4};
} else if (userParameter == "Y") {
    grouping = g => new {g.Month, Option1 = g.prop5, Option2 = g.prop6};
}

Then I'm passing grouping into the querty above. The problem is that I have an anonymous type in the grouping and Expression<Func<Report_Data, TResult>> errors when I use TResult as the Result Type.

Is there a way to use this expression delegate format and specify a generic or anonymous result type? (preferably without having to create a class for every result type) Or should I be allowing different groupings by some other mechanism?

Following an explanation from this blog post on building LINQ Queries , I was find a solution as follows:

Extend LINQ:

public static class Linq {
    public static Expression<Func<T, R>> 
        Expr<T, R>(Expression<Func<T, R>> f) {
        return f;
    }
}

The grouping can then be set like this:

var grouping = Linq.Expr((Report_Data g) => new {g.Month, Option1 = g.prop1, Option2 = g.prop2});

if (userParameter == "X") {
    grouping = Linq.Expr((Report_Data g) => new {g.Month, Option1 = g.prop3, Option2 = g.prop4});
} else if(userParameter == "Y") {
    grouping = Linq.Expr((Report_Data g) => new {g.Month, Option1 = g.prop5, Option2 = g.prop6});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM