i'm having a List<String>
like
List<String> MyList=new List<String>
{
"101010",
"000000",
"111000"
};
I need to create a new list (List<String>
) with "MyList" . so the rows in the "MyList" becomes columns in the new List and the columns become rows
So the result will be l开发者_C百科ike
{
"101",
"001",
"101",
"000",
"100",
"000"
}
now i'm using nested for
loop to do this.
Is there any way to do this using LINQ
or LAMBDA
expression
Here's a LINQPad script that does the trick:
void Main()
{
List<String> MyList = new List<String>
{
"101010",
"000000",
"111000"
};
Transpose(MyList).ToList().Dump();
}
static IEnumerable<String> Transpose(IEnumerable<String> strings)
{
return from i in Enumerable.Range(0, strings.First().Length)
select new string((from s in strings select s[i]).ToArray());
}
Output:
101
001
101
000
100
000
int n = myList[0].Length; // or whatever
var transposed = from ind in Enumerable.Range(0, n)
let sb = new StringBuilder()
select myList.Select(s => s[ind]).Aggregate(sb, (acc, next) => acc.Append(next));
foreach (var s in transposed)
Console.WriteLine(s);
var transposed = Enumerable.Range(0, MyList.First().Length)
.Select(rowIndex => new string(MyList.Select(str => str[rowIndex]).ToArray()))
.ToList();
Of course, this will break if the strings are not of identical length.
精彩评论