Linq按查询分组结果

时间:2014-07-07 14:46:28

标签: c# linq

我有以下例子:

Model mod1 = new Model {  Header = "A", canDelete = true,pax=1 };
Model mod2 = new Model {  Header = "B", canDelete = true,pax=1 };
Model mod3 = new Model {  Header = "A", canDelete = true,pax=2 };
Model mod4 = new Model {  Header = "B", canDelete = false,pax=2 };
Model mod5 = new Model {  Header = "A", canDelete = true,pax=3 };
Model mod6 = new Model {  Header = "B", canDelete = false,pax=3 };
Model mod7 = new Model {  Header = "A", canDelete = false,pax=4 };
Model mod8 = new Model {  Header = "B", canDelete = true,pax=4 };

我将这些模型添加到listMod

我想先用pax编号分组,所以我使用了:

var resultQuery = listMod.GroupBy(p=>p.pax);

如何通过Header和canDelete重新对resultQuery的结果进行分组?

目标是有3组:

1st group : mod1 and mod2
2nd group : mod3 , mod4 , mod5 and mod6
3rd group : mod7 and mod8

1 个答案:

答案 0 :(得分:1)

嗯,可能有更好的方法,但这个方法应该有效,假设每个pax号总有两个项目。

"技巧"是连接按canDelete分组的第一个和第二个Header / pax项对,并对该值进行分组。

比组内的列表更平坦(使用SelectMany

listMod.GroupBy(m => m.pax)
    .Select(m => new
            {
                 valuePair = string.Format("{0}-{1}/{2}-{3}", m.First().canDelete, m.First().Header, m.Last().canDelete, m.Last().Header),
                 value = m.Select(x => x)
            })
    .GroupBy(m => m.valuePair)
    .Select(g => g.SelectMany(x => x.value))
    //.ToList();

如果你想避免这种糟糕的连接,你也可以

var result = listMod
                 .GroupBy(m => m.pax)
                 .Select(m => new
                 {
                      a1 = m.First().canDelete,
                      a2 = m.First().Header,
                      b1 = m.Last().canDelete,
                      b2 = m.Last().Header,
                      value = m.Select(x => x)
                  })
                  .GroupBy(m => new {m.a1, m.a2, m.b1, m.b2})
                  .Select(g => g.SelectMany(x => x.value))
                  //.ToList();