简体   繁体   English

C#:如何操纵List <String> 使用LINQ或LAMBDA表达式

[英]C#: How to manipulate List<String> using LINQ or LAMBDA expression

i'm having a List<String> like 我有一个List<String>类的

 List<String> MyList=new List<String>
    {
    "101010",
    "000000",
    "111000"
    };

I need to create a new list ( List<String> ) with "MyList" . 我需要使用“MyList”创建一个新列表( List<String> )。 so the rows in the "MyList" becomes columns in the new List and the columns become rows 所以“MyList”中的行成为新List中的列,列成为行

So the result will be like 所以结果就像

 {
    "101",
    "001",
    "101",
    "000",
    "100",
    "000"
  }

now i'm using nested for loop to do this. 现在我使用nested for循环来做到这一点。

Is there any way to do this using LINQ or LAMBDA expression 有没有办法使用LINQLAMBDA表达式来做到这一点

Here's a LINQPad script that does the trick: 这是一个LINQPad脚本,可以解决这个问题:

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. 当然,如果琴弦的长度不同,这将会中断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM