有没有其他方法可以将行字段转换为除pivot之外的列

时间:2014-09-25 13:50:51

标签: c# asp.net-mvc linq

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

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

谁能告诉我怎样才能实现这一目标?我已经尝试过使用数据透视表,但我最终错误地将一个通用列表转换为字符串。我想将其返回到我的视图页面的列表中。

我的代码如下所示:

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

1 个答案:

答案 0 :(得分:0)

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

/*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