there is an array, for example, 1 2 3 4 5 6. It is necessary using only LINQ extension methods to turn it into an array of 3 7 11. If there are an odd number of elements, then the element with the last index is simply transferred.

In general, a common question. The bottom line is working with array elements, taking into account the entire array.

  • I did not quite understand what result was needed for a list of 1 2 10 (an odd number of elements). - VladD

4 answers 4

https://ideone.com/jJcaqy

using System; using System.Linq; public class Test { public static void Main() { int[] a = {1, 2, 3, 4, 5, 6}; var res = a.Select((x, i) => new {x, i}).GroupBy(x => xi >> 1, x=> xx).Select(x => x.Sum()); Console.WriteLine(string.Join(" ", res)); } } 

But in general, it is necessary to do humanly with your hands in a cycle.

  • cool I just found a solution, only through Aggregate () instead of GroupBy () :) - iRumba

You can do this:

 var list = new List<int> { 1, 2, 3, 4, 5, 6 }; var transformedList = list.Where((item, i) => i % 2 == 0). Zip(list.Where((item, i) => i % 2 != 0), (first, second) => first + second).ToList(); if(list.Count%2 != 0) transformedList.Add(list[list.Count - 1]); foreach(var item in transformedList) Console.WriteLine(item); 
  • and in one line? Without If (*** - iRumba

A practical solution is to use the MoreLinq package:

 var list = new List<int> { 1, 2, 3, 4, 5, 6 }; var sums = list.Batch(2, batch => batch.Sum()); 

This code for the case of an odd number of elements in the last sum includes only one, the last element.

If for an odd number of elements the last element does not need to be included in the result, a slightly more complex code is needed:

 var sums = list.Batch(2).Where(b => b.Count() == 2).Select(b => b.Sum()); 
  • a link to the sea links :) - Grundy
  • one
    @Grundy: Just added :) - VladD
  • Will this solution handle an odd number? - ixSci
  • @ixSci: With the latest update - yes :) - VladD
  • one
    @iRumba, you should always remember that your LINQ reading skill may differ from the programmer's skill that will read your code. A few LINQ floors are terrible for any programmer, no matter how tough his qualifications are. If floors appear, then it is necessary to break into variables or even functions. - ixSci

For completeness, here’s another lazy solution with a loop.

 static IEnumerable<int> ComputePairSums(IEnumerable<int> seq) { int prev = 0; bool hasPrev = false; foreach (var e in seq) { if (hasPrev) yield return prev + e; else prev = e; hasPrev = !hasPrev; } // если нужно возвращать последний элемент для нечётного к-ва элементов, то: if (hasPrev) yield return prev; } var list = new List<int> { 1, 2, 3, 4, 5, 6, 7 }; var sums = ComputePairSums(list); foreach (var v in sums) Console.WriteLine(v);