Lambda表达式中的嵌套Group-By没有得到预期的结果
本文关键字:结果 表达式 嵌套 Group-By Lambda | 更新日期: 2023-09-27 18:12:21
我有一个MySQL表,它有如下所示的数据
Column1 Column2 Column3
AAA ABC 123
AAA ABC 234
AAA DEF 1111
AAA DEF 2222
我试图从它创建JSON数据。预期的JSON结果为:
AAA
ABC
123
234
DEF
1111
2222
想使用嵌套的group by语句,但无法达到预期的结果。请帮助我形成JSON字符串。执行嵌套的规则如下:
父母->多个子女->多个孙辈
你可以试试这个
使用GroupBy var result = list.GroupBy(x => x.Column1).Select(y => new
{
C1 = y.Key,
C1Children = y.GroupBy(z => z.Column2).Select(m => new
{
C2 = m.Key,
C2Children = m.Select(n => n.Column3)
})
});
JavaScriptSerializer serializer = new JavaScriptSerializer();
var jsonResult = serializer.Serialize(test);
没有GroupBy var result = list.Select(x => x.Column1).Distinct().Select(y => new
{
Level1 = y,
Level2List = list.Where(z => z.Column1 == y).Select(y1 => y1.Column2).Distinct().Select(z1 => new
{
Level2 = z1,
Level3List = list.Where(m => m.Column2 == z1).Select(n => n.Column3)
})
}).ToList();
JavaScriptSerializer serializer = new JavaScriptSerializer();
var jsonResult = serializer.Serialize(result);
感谢您的宝贵支持。我用下面的lambda表达式解决了这个问题。
var disp = menu.GroupBy(a => a.col1).Select(b => b.First()).Select(c => new BL.Objects.menu()
{id = c.id,
name = c.col1,
items = menu.Where(f => f.col1 == c.col1).GroupBy(g => g.col2).Select(g => g.FirstOrDefault()).Select(j => new BL.Objects.submenu()
{id = j.id,
name = j.col2,
items = menu.Where(k => k.col2 == j.col2 && k.col1 == c.col1).Select(l => new BL.Objects.sub_submenu()
{id = l.id,
name = l.col3
})
})
});
var jsonResult = System.Web.Script.Serialization.JavaScriptSerializer().Serialize((disp);