LoginSignup
6
4

More than 5 years have passed since last update.

2次元配列を列で取り出して演算する

Posted at

2次元配列を縦に取り出して合計とりたいなぁとか平均とりたいなぁとか思ってしまうことがあります。
そんなときに1行で書きたいなぁと思ったら、以下のようにします。

var tmp = a.SelectMany(
    x => x.Select((item, index) => new { item, index }))
    .GroupBy(y => y.index, (key, z) => { return /*ここに演算方法を記述*/ }
);

例えば、平均を計算したい場合は以下のようにします。

double[][] a = new double[][]{
    new  double[]{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
    new  double[]{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
    new  double[]{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
};

var tmp = a.SelectMany(
    x => x.Select((item, index) => new { item, index }))
    .GroupBy(y => y.index, (key, z) => { return z.Average(n => n.item); }
);
6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4