c# - Grouping based on the order of data -
i have set of data in following format.
a b c b b c
i want group data in such way result should grouped alphabet , should based on order. example above data output should be
a - 2 b - 1 - 1 c - 1 b - 2 c - 1
create variables keep track of last letter , count. loop on letters , emit data whenever letter changes.
list<char> letters = new list<char>() { 'a', 'a', 'b', 'a', 'c', 'b', 'b', 'c' }; char last = letters.first(); int count = 1; foreach (char letter in letters.skip(1)) { if (letter == last) { count++; } else { console.writeline(last + " - " + count); last = letter; count = 1; } } console.writeline(last + " - " + count);
the first character handled outside of loop setting last = letters.first()
, foreach
loop starts second character calling letters.skip(1)
.
the last console.writeline
there handle final character block.
Comments
Post a Comment