Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string to List<string> with Linq

Tags:

c#

list

linq

I'd like avoid loop

I have this :

string s = "AAAA,12,BBBB,34,CCCCC,56";

With Linq, I'd like to have 2 List

In the first : AAAA, BBBB and CCCCC

In the second : 12,34 and 56

It's not based on numeric or not numeric.

Thanks,

like image 485
Kris-I Avatar asked Sep 29 '10 12:09

Kris-I


3 Answers

Lets use Aggregate for the fun of it (and also, to prove this can be done as a single expression):

"AAAA,12,BBBB,34,CCCC,56".Split(',').Aggregate(
    new { Uneven = new List<string>(), Even = new List<string>() },
    (seed, s) => { 
        if (seed.Uneven.Count > seed.Even.Count) 
            seed.Even.Add(s);
        else
            seed.Uneven.Add(s);
        return seed;
    });

According to LINQPad, the result is this: alt text

Of course I probably wouldn't do it this way, as it's kind of hard to read. And the testing for which list to append to is, well, not nice.

But at least we now have another example of lambda statements - normally the LINQ literature tries to forget them (probably because they won't work with SQL or any other backend that uses expression trees).

One advantage of this method as opposed to the cleaner solutions above is that this only makes one pass through the list. Since we are splitting a string, though, I'd try optimizing somewhere else ;) Wouldn't a IEnumerable<string> Split(this string self, string boundary) be cool?

like image 115
Daren Thomas Avatar answered Oct 21 '22 09:10

Daren Thomas


You can use

var str = "AAAA,12,BBBB,34,CCCCC,56";

var spl = str.Split(',');
var l1 = spl.Where((x, y) => y % 2 == 0).ToList();
var l2 = spl.Where((x, y) => y % 2 == 1).ToList();

This is going to check if the index is even or odd.

like image 35
BrunoLM Avatar answered Oct 21 '22 07:10

BrunoLM


Given that the rule is that you want every second string in one list and the others in another list, you can do something like this:

        string s = "AAAA,12,BBBB,34,CCCCC,56";

        var parts = s.Split(',');

        var first = parts.Where((p, i) => i % 2 == 0);
        var second = parts.Where((p, i) => i % 2 == 1);
like image 6
Klaus Byskov Pedersen Avatar answered Oct 21 '22 09:10

Klaus Byskov Pedersen