我在数据库中有一个表,我将通过 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
关于c# - 除了 pivot 之外,还有其他方法可以将行字段转换为列吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26040349/