gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:50:35 26 4
gpt4 key购买 nike

我在数据库中有一个表,我将通过 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com