LINQ GROUPBY - 如何在运行时指定分组键? [英] Linq GroupBy - how to specify the grouping key at runtime?

查看:204
本文介绍了LINQ GROUPBY - 如何在运行时指定分组键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有做一个LINQ的好办法 GROUPBY ,其中分组关键是在运行时确定的?例如我想分组键从字段的用户选择列表中建 - 你可以做到这一点?我知道我可以很容易地做到这一点,如果我将所有的都以字符串的表,但我不知道是否有一个优雅的或聪明的方式,否则实现这一目标。

is there a good way to do a Linq GroupBy where the grouping key is determined at runtime? e.g. I want the grouping key to be built from a user-selected list of fields - can you do this? I know I can do it easily if I convert everything to a table of strings, but I was wondering if there was an elegant or clever way to accomplish this otherwise.

class Item
{
    public int A, B;
    public DateTime D;
    public double X, Y, Z;
}



我有一个列表<项目> 名为数据。我想要做的事情一样检索 X A 组合,或 X ,以Z ,由一个和 B 。但进入分组哪些领域应该能够以某种方式运行时指定。

I have a List<Item> called data. I want to do things like retrieve the sum of X grouped by A, or the sums of X, Y, and Z, grouped by A and B. but what fields go into the grouping should be able to be specified at runtime in some way.

推荐答案

获得的动态LINQ 代码,并使用来自它的扩展,它允许你指定一个字符串的KeySelectors。

Get the Dynamic LINQ code and use the extension from it that allows you to specify the keySelector with a string.

var query = db.Foo.GroupBy( "{0}", "GroupedProperty", groupKey );

您可能还需要考虑添加自己的扩展,如果你想找回被分组整个对象的关键。

You might also want to consider adding your own extension if you want to get back the entire object grouped by the key.

public static IQueryable GroupByComplete( this IQueryable source, string keySelector, params object[] values )
{
    if (source == null) throw new ArgumentNullException( "source" );
    if (keySelector == null) throw new ArgumentNullException( "keySelector" );
    LambdaExpression keyLambda = DynamicExpression.ParseLambda( source.ElementType, null, keySelector, values );
    return source.Provider.CreateQuery(
        Expression.Call(
            typeof( Queryable ), "GroupBy",
            new Type[] { source.ElementType, keyLambda.Body.Type },
            source.Expression, Expression.Quote( keyLambda ) ) );
}

这篇关于LINQ GROUPBY - 如何在运行时指定分组键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆