【问题标题】:Multiple Column to Row [closed]多列到行[关闭]
【发布时间】:2016-06-23 07:54:06
【问题描述】:

Raw data
根据第一张图片,我在数据表中有数据,但想要转换我的数据表或使用第二张图片中的新输出创建一个新的数据表

                var reportData = (from C in Table1
                                  join LC in Table2 on C.Id equals LC.Id
                                  select new { C.Id, C.User, LC.Phy, LC.Che, LC.Bio, LC.Math }).ToList();

                foreach (var item in reportData)
                {

                    lstLc.Add(new Launch() { Username= item.User, Phy = item.Phy, Che = item.Che, Bio = item.Bio, Math = item.Math });
        }

原始数据:Output needed

User    Phy    Che    Bio    Math
A       12     20     16     10
B       15     19     18     20
C       13     17     11     18

需要输出..

User    Type    value
A       Phy     12
A       Che     20
A       Bio     16
A       Math    10
B       Phy     15
B       Che     19
B       Bio     18
B       Math    20
C       Phy     13
C       Che     17
C       Bio     11
C       Math    18

【问题讨论】:

  • 问题是什么?
  • 我在数据表中有第一张图片中的数据,但想转换我的数据表或创建一个新的数据表,其中包含第二张图片中的新输出。
  • 你明白这是一个请求,而不是一个问题的问题吗?不仅如此,你甚至不提供一些代码来使用。这些数据保存在哪里?

标签: c# asp.net linq lambda


【解决方案1】:

你可以像这样使用union

SELECT User, Type, value FROM (
    SELECT User, 'Phy' AS 'Type', Phy AS 'value' FROM table1
    UNION
    SELECT User, 'Che' AS 'Type', Che AS 'value' FROM table1
    UNION
    SELECT User, 'Bio' AS 'Type', Bio AS 'value' FROM table1
    UNION
    SELECT User, 'Math' AS 'Type', Math AS 'value' FROM table1
) AS t
ORDER BY User

在 LINQ 中,您可以执行以下操作:

var list = entity.Select(e => new { User = e.User, Type = "Phy", value = e.Phy })
    .Union(entity.Select(e => new { User = e.User, Type = "Che", value = e.Che }))
    .Union(entity.Select(e => new { User = e.User, Type = "Bio", value = e.Bio }))
    .Union(entity.Select(e => new { User = e.User, Type = "Math", value = e.Math }))
    .OrderBy(e => e.User);

编辑将您的代码更改为:

var repFlatData = (from C in Table1
                   join LC in Table2 on C.Id equals LC.Id
                   select new { C.Id, C.User, LC.Phy, LC.Che, LC.Bio, LC.Math }).ToList();

var reportData = repFlatData.Select(e => new { User = e.User, Type = "Phy", value = e.Phy })
          .Union(repFlatData.Select(e => new { User = e.User, Type = "Che", value = e.Che }))
          .Union(repFlatData.Select(e => new { User = e.User, Type = "Bio", value = e.Bio }))
          .Union(repFlatData.Select(e => new { User = e.User, Type = "Math", value = e.Math }))
          .OrderBy(e => e.User);

foreach (var item in reportData) {
    lstLc.Add(new Launch() { Username= item.User, Type = item.Type, Value = item.Value });
}

当然,您需要将 Launch 类更改为仅包含列(用户名、类型、值)。

【讨论】:

  • 我想在 ASP.net 中使用 Lambda 查询而不是在 SQL 中。
  • 谢谢拉西尔。我已经编辑了我的问题,还用 C# 编写了实际代码。所以你能帮我解决同样的代码吗?因为我是 Asp.net 的新手。
  • 查看我编辑的答案。
  • 非常感谢 Racil.. 现在可以使用了...
猜你喜欢
  • 2022-10-13
  • 2021-05-14
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 2011-03-12
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多