使用Linq创建交叉表结果 [英] Using Linq to create crosstab results

查看:77
本文介绍了使用Linq创建交叉表结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
是否可以使用LINQ进行数据透视?

Possible Duplicate:
Is it possible to Pivot data using LINQ?

我想知道是否完全可以使用Linq创建交叉表样式的结果. 我有一些看起来像下面的数据:

I'm wondering if its at all possible to create crosstab style results with Linq. I have some data that looks like the following:

    var list = new[]
    {
        new {GroupId = 1, Country = "UK", Value = 10},
        new {GroupId = 1, Country = "FR", Value = 12},
        new {GroupId = 1, Country = "US", Value = 18},
        new {GroupId = 2, Country = "UK", Value = 54},
        new {GroupId = 2, Country = "FR", Value = 55},
        new {GroupId = 2, Country = "UK", Value = 56}
    };

并且我正尝试将类似以下内容的内容输出到中继器控件:

and I'm trying to output to a repeater control something like the following:

GroupId.....UK.....FR.....US
1...........10.....12.....18
2...........54.....55.....56

它是导致我遇到问题的动态列.有什么解决办法吗?

Its the dynamic columns that are causing my problems. Any solutions to this?

推荐答案

您需要一个runtimy类来保存这些runtimy结果. xml怎么样?

You need a runtimy class to hold these runtimy results. How about xml?

XElement result = new XElement("result",
  list.GroupBy(i => i.GroupId)
  .Select(g =>
    new XElement("Group", new XAttribute("GroupID", g.Key),
      g.Select(i => new XAttribute(i.Country, i.Value))
    )
  )
);

您是否希望每个结果单元格有多个记录?如果是这样的话,那将需要在其中进行一些求和(和更多分组).

Are you expecting multiple records per result cell? If so there would need to be some Summing (and more grouping) in there.

(此答案是概念证明,而不是最终结果.有几个问题要解决,例如:列的排序,缺少的单元格等).

(this answer is proof of concept, not final result. There's several issues to address, such as: ordering of columns, missing cells, and so on).

这篇关于使用Linq创建交叉表结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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