本文介绍了通过运行时已知的多个键进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个telerik网格,可以将对象列表数据绑定到页面上.用户可以在查看数据时根据自己的喜好对列进行分组.我正在编写一个功能以在excel文档中导出此数据,并希望保留用户在页面上的分组.我可以获取用户分组的对象的属性的字符串名称.

I have a telerik grid that I databind a list of objects to on a page. The users can group columns to their liking when viewing the data. I am writing a function to export this data in an excel document and would like to preserve the grouping that the user has on the page. I am able to get the string names of the properties of my objects that the user has grouped by.

我遇到的问题是如何在运行时进行分组.有很多这样的示例:使用lambda通过多个列进行分组描述如何提前知道在编译期间如何对多个属性进行分组.但是,直到运行时,我才知道如何分组.

What I am stuck on is how to do the grouping during runtime. There are plenty of examples such as this: Group by with multiple columns using lambda describing how to group by multiple properties during compile time when you know ahead of time. I however, do not know what to group by until during run time.

在运行时是否有关于分组的建议?

Is there any suggestions on how to go about grouping during runtime?

推荐答案

我将使用Dynamic Linq( http://weblogs.asp.net/scottgu/dynamic-linq-part-1-using-the-linq-dynamic-query-library )

I would do this with Dynamic Linq (http://weblogs.asp.net/scottgu/dynamic-linq-part-1-using-the-linq-dynamic-query-library)

示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic; //have to install this via nuget or download it

public class Person {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DOB { get; set; }
}


class Program {
    static void Main(string[] args) {
        var peeps = new List<Person>{
            new Person(){ FirstName="Tim", LastName="Smith", DOB = DateTime.Now},
            new Person(){ FirstName="Tim", LastName="Smith", DOB = DateTime.Now.AddDays(1)},
            new Person(){ FirstName="Mike", LastName="Smith", DOB = DateTime.Now.AddDays(2)},
            new Person(){ FirstName="Frank", LastName="Jones", DOB = DateTime.Now.AddDays(3)},
        };

        var eq = peeps.GroupBy("new (LastName, FirstName)", "it").Select("new(it.Key as Key, it as People)"); ;
        foreach (dynamic el in eq) {
            Console.WriteLine(el.Key);
            foreach (var person in el.People as IEnumerable<Person>) {
                Console.WriteLine(person.LastName + " " + person.DOB);
            }
        }
    }
}

这篇关于通过运行时已知的多个键进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 06:28