c# - Split list by element -


i have list of 1 , 0 this:

var list = new list<int>{1,1,1,0,1,1,0,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,0,1} 

between 2 items, can 1 zero. how split list sublists 0?

other words: if have string this: string mystring = "111011011110111111011101" easy split 0 few strings. how list? example shoudl produce these sublists:

1,1,1 1,1 1,1,1,1 1,1,1,1,1,1 1,1,1 1 

so there better way casting each element string, joining them , doing show can done string ?

you can solve problem transforming input sequence sequence of sequences linq groupby does. however, in case grouping on change in input sequence. there perhaps possibility of combining existing linq operators groupby, zip , skip want think easier (and performs better) create iterator block looks @ pairs of items in input sequence:

static class enumerableextensions {    public static ienumerable<ienumerable<t>> grouponchange<t>(     ienumerable<t> source,     func<t, t, boolean> changepredicate   ) {     if (source == null)       throw new argumentnullexception("source");     if (changepredicate == null)       throw new argumentnullexception("changepredicate");      using (var enumerator = source.getenumerator()) {       if (!enumerator.movenext())         yield break;       var firstvalue = enumerator.current;       var currentgroup = new list<t>();       currentgroup.add(firstvalue);       while (enumerator.movenext()) {         var secondvalue = enumerator.current;         var change = changepredicate(firstvalue, secondvalue);         if (change) {           yield return currentgroup;           currentgroup = new list<t>();         }         currentgroup.add(secondvalue);         firstvalue = secondvalue;       }       yield return currentgroup;     }   }  } 

grouponchange take items in input sequence , group them sequence of sequences. new group started when changepredicate true.

you can use grouponchange split input sequence want to. have remove groups have 0 value using where.

var groups = items   .grouponchange((first, second) => first != second)   .where(group => group.first() != 0); 

you can use approach if input class instances , want group property of class. have modify predicate accordingly compare properties. (i know need because asked deleted question more complicated input sequence not numbers classes number property.)


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -