2016-08-05 1 views
1

このコード部分をLINQに変換したいと考えています。 誰でも助けてくれますか?リスト<int[]>のすべての配列またはインデックスを経てギザギザの配列を合計するにはどうすればいいですか?

var list = new List<int[]>(); 
list.Add(new int[] { 1, 2, 3, 4 }); 
list.Add(new int[] { 5, 4, 2, 1 }); 
list.Add(new int[] { 5, 9, 3, 5 }); 

var result = new int[4]; 
foreach (var item in list) 
{ 
    for (int i = 0; i < 4; i++) 
    { 
     result[i] += item[i]; 
    } 
} 

結果がでなければなりません:{ 11, 15, 8, 10 }それは和の結果であるため、私の頭にポップ

+0

http://stackoverflow.com/questions/38783931/one-linq-query-that-equals-to-two-inner-loop – Sherlock

+0

の可能重複そして、これが正しい答えはhttpです:// stackoverflowの.com/a/17050509/4827151 – Sherlock

+0

@Sherlock、私はリンクを見上げて、tは非常によく似ていて、助けてくれました –

答えて

3

私はこれが最も読みやすいバージョンだと思います。

int[] result = Enumerable.Range(0, 4) 
    .Select(index => list.Sum(arr => arr[index])) 
    .ToArray(); 

OPもforループ使用しているので、0-3から、それらはすべて同じ大きさを持っているように見える:GroupByする必要はありません、あなたはすべての配列のSumごとにインデックスすることができます。

それはあなたがこのスーパー安全なアプローチを使用することができます場合はない場合:

int maxLength = list.Max(arr => arr.Length); 
int[] result = Enumerable.Range(0, maxLength) 
    .Select(index => list.Sum(arr => arr.ElementAtOrDefault(index))) 
    .ToArray(); 
+0

これは、サブアレイは同じ長さを持っています – tym32167

+1

@ tym32167:そうかもしれない、OPは0-3からのfor-loopも使用しています –

+0

はい、本当です。将来の読者のためにそれを念頭に置いてください。 – tym32167

2

まず最初:

var list = new List<int[]>(); 
list.Add(new int[] { 1, 2, 3, 4 }); 
list.Add(new int[] { 5, 4, 2, 1 }); 
list.Add(new int[] { 5, 9, 3, 5 }); 

var result = list.SelectMany(item => item.Select((innerItem, index) => new { index, innerItem })) 
        .GroupBy(item => item.index, (key, group) => group.Sum(item => item.innerItem)) 
        .ToList(); 

上記ティムのアプローチがきれいで、

優れています
+0

不要なアクションとより多くのメモリを消費するための不要なgroupby – gabba

0

これを試すことができます

var list = new List<int[]>(); 
list.Add(new int[] { 1, 2, 3, 4 }); 
list.Add(new int[] { 5, 4, 2, 1 }); 
list.Add(new int[] { 5, 9, 3, 5 }); 

var result = list.SelectMany(x => x.Select((z, i) => new {z, i})) 
    .GroupBy(x=>x.i).Select(x=>x.Sum(z=>z.z)).ToArray();  
0

は、集約を行うにしたいので、なぜLINQの集計を使用していないだろうか?

 var list = new List<int[]>(); 
     list.Add(new int[] { 1, 2, 3, 4 }); 
     list.Add(new int[] { 5, 4, 2, 1 }); 
     list.Add(new int[] { 5, 9, 3, 5 }); 

     var addArrayValues = new Func<int[], int[], int[]>(
      (source, destination) => 
      { 
       for (int i = 0; i < source.Length; i++) 
        destination[i] += source[i]; 

       return destination; 
      }); 

     var aggregateResult = list.Aggregate(new int[4], 
      (accumulator, current) => addArrayValues(current, accumulator)); 
関連する問題