c# - 除了 pivot 之外,还有其他方法可以将行字段转换为列吗

标签 c# asp.net-mvc linq

我在数据库中有一个表,我将通过 View 模型访问它,而不是直接访问域模型。我的表看起来像这样:

placename       cafeName
  x               cafe red
  x               cafe blue
  y               cafe red
  y               cafe blue
  z               cafe red
  z               cafe blue

我想要这样的东西:

placename         cafename   cafe name
  x               cafe red   cafe blue
  y               cafe red   cafe blue
  z               cafe red   cafe blue

谁能告诉我怎样才能做到这一点?我已经尝试过使用数据透视表,但最终在将通用列表转换为字符串时出错。我想将其返回到我的 View 页面的列表中。

我的代码是这样的:

 var query = from ast in db.mytable                                            
        select new ActViewModel
        {
            ScreenSetupID = ast.SetupID,
            Acame = ast.Acame             
        };
        var result = query.ToList();
        return result;

最佳答案

简单的枢轴有什么问题?这个解决方案在任何方面都不是通用的,但应该给你一个好的开始:

/*Thank you Daniel. J.G for the fiddle. I took it as the basis*/
public class Foo
{
    public String Place {get; set;}
    public String CafeName {get; set;}
}

List<Foo> RawFoos = new List<Foo>()
{
    new Foo{Place = "x", CafeName = "cafe red"},
    new Foo{Place = "x", CafeName = "cafe blue"},
    new Foo{Place = "y", CafeName = "cafe red"},
    new Foo{Place = "y", CafeName = "cafe blue"},
    new Foo{Place = "z", CafeName = "cafe red"},
};

var pivot = from f in RawFoos
            group f.CafeName by f.Place into g
            //Anonymous object because I'm lazy      
            select new 
            { 
              Place = g.Key,
              CafeRed = g.FirstOrDefault(x => x == "cafe red"),
              CafeBlue = g.FirstOrDefault(x => x == "cafe blue")
            };

pivot.Dump(); // only in Linqpad

enter image description here

关于c# - 除了 pivot 之外,还有其他方法可以将行字段转换为列吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26040349/

相关文章:

c# - EntityKey 属性只能在属性的当前值为 null 时设置

@Url.action() 的 ASP.NET MVC 帖子

asp.net-mvc - datatype.text 验证什么?

sql - LINQ 到 SQL : Issue with concurrency

LINQ:我们可以从层次结构创建一个平面列表吗

c# - WPF - MVVM 文本框限制为特定字符

c# - Visual Studio 单元测试 : run initialization code before each test

c# - 具有 DependencyProperty 的最简单 WPF UserControl 中的内存泄漏

asp.net-mvc - 从 MVC Controller 返回 Json 数据

c# - 如何使用 LINQ 在函数中定义返回类型?