c# - "Turning" an IEnumerable<IEnumerable<T>> 90 degrees -
what i'm looking basic operation (which i'm sure have name i'm unaware of atm). have matrix like:
{1,2,3}
{a,n,f}
{7,8,9}
which i'd mutate into
{1,a,7}
{2,n,8}
{3,f,9}
(the above identifiers objects not real values. actual objects of same type , unordered)
i'd prefer declarative solution speed factor. i'm going have turn quite few tables (100k cells min) , slow version on critical path.
however i'm still more interested in readable solution. i'm looking alternative solutions below. (by alternative not mean variations different approach)
var arrays = rows.select(row => row.toarray()); var cellcount = arrays.first().length; for(var = 0;i<cellcount;i++){ yield return getrow(i,arrays); } ienumerable<t> getrow(int i,ienumerable<t[]> rows){ foreach(var row in rows}{ yield return row[i]; } }
amongst 2 equally readable solutions i'd go faster readability goes before speed
edit square matrix
i'm little iffy implementation. has side-effects local iterator looks logically clean me. assumes each sequence same length should work any. can think of variable length zip()
method. should perform better other linked linq solutions found in other answers uses minimum operations needed work. better without use of linq. might considered optimal.
public static ienumerable<ienumerable<t>> transpose<t>(this ienumerable<ienumerable<t>> source) { if (source == null) throw new argumentnullexception("source"); var enumerators = source.select(x => x.getenumerator()).toarray(); try { while (enumerators.all(x => x.movenext())) { yield return enumerators.select(x => x.current).toarray(); } } { foreach (var enumerator in enumerators) enumerator.dispose(); } }
Comments
Post a Comment