Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

lambda

linq

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 like

 {
    "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

like image 640
Thorin Oakenshield Avatar asked Feb 27 '26 19:02

Thorin Oakenshield


1 Answers

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
like image 142
Lasse V. Karlsen Avatar answered Mar 01 '26 10:03

Lasse V. Karlsen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!