变换集合 [英] Transform a collection

查看:153
本文介绍了变换集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
  });

这篇关于变换集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆