变换集合

由网友(82年的小可爱)分享简介:有对象的集合。用示意图来表示:Have a collection of objects. Schematically:[{ A = 1, B = 1 }{ A = 1, B = 2 }{ A = 2, B = 3 }{ A = 2, B = 4 }{ A = 1, B = 5 }{ A = 3, B = 6 }]...

有对象的集合。用示意图来表示:

Have a collection of objects. Schematically:

[
    { A = 1, B = 1 }
    { A = 1, B = 2 }
    { A = 2, B = 3 }
    { A = 2, B = 4 }
    { A = 1, B = 5 }
    { A = 3, B = 6 }
]

极品:

[
    { A = 1, Bs = [ 1, 2 ] }
    { A = 2, Bs = [ 3, 4 ] }
    { A = 1, Bs = [ 5 ] }
    { A = 3, Bs = [ 6 ] }
]

是否有可能LINQ这样?

Is it possible to LINQ such?

注意:顺序很重要。因此, BS = [5] 不能与 BS =合并[1,2]

Note: Ordering is important. So Bs = [5] can't be merged with Bs = [1, 2]

推荐答案

鉴于这些简单的类:

class C {
  public int A;
  public int B;
}
class R {
  public int A;
  public List<int> Bs = new List<int>();
}

您可以做到这一点是这样的:

You can do it like this:

var cs = new C[] {
  new C() { A = 1, B = 1 },
  new C() { A = 1, B = 2 },
  new C() { A = 2, B = 3 },
  new C() { A = 2, B = 4 },
  new C() { A = 1, B = 5 },
  new C() { A = 3, B = 6 }
};

var rs = cs.
  OrderBy(o => o.B).
  ThenBy(o => o.A).
  Aggregate(new List<R>(), (l, o) => {
    if (l.Count > 0 && l.Last().A == o.A) {
      l.Last().Bs.Add(o.B);
    }
    else {
      l.Add(new R { A = o.A, Bs = { o.B } });
    }
    return l;
  });

注意:在上面我假设货币,然后由于必须进行排序。如果不是这样,它的去除排序说明一个简单的问题:

Note: In the above I assume that the Bs and then the As have to be sorted. If that's not the case, it's a simple matter of removing the sorting instructions:

var rs = cs.
  Aggregate(new List<R>(), (l, o) => {
    if (l.Count > 0 && l.Last().A == o.A) {
      l.Last().Bs.Add(o.B);
    }
    else {
      l.Add(new R { A = o.A, Bs = { o.B } });
    }
    return l;
  });
阅读全文

相关推荐

最新文章