c# - Repeat values Linq -


let's have numbers sequence:

 2 5 7 8 0 0 0  

and want following sequence:

2 5 7 8 8 8 8 

that is: repeat last number before zeros, can accomplished linq ?

thank in advance

generally speaking, no. can write own:

public static class someextension {     public static ienumerable<t> replacedefaultbypreviousnondefault(this ienumerable<t> sequence)     {         t previous = default(t);          foreach(var val in squence)         {             if(val == default(t)) yield return previous;              previous = val;              yield return val;                 }     } } 

example usage:

var numbers = new int[] { 2, 5, 7, 8, 0, 0, 0 };  var result = numbers.replacedefaultbypreviousnondefault(); 

if really insist on artificially introducing linq method, take above loop , build select:

  var numbers = new int[] { 2, 5, 7, 8, 0, 0, 0 };    int last = 0;   var result = numbers.select(n => n == 0 ? last : last = n); 

Comments