简体   繁体   中英

String list with comma separated values to int list

As part of a larger program I need to convert a string list with comma separated values to an Int list where the information must be arranged in a particular way. In other words, I have this string listA:

**ListA(string)**

[0] "4, 0, 7, -1,"  

[1] "0, 1, 7, -1,"  

[2] "7, 1, 6, -1,"  

That I want to convert into this int ListB:

**List B(int)**

 [0]    {int[4]}    

        [0] 4   
        [1] 0   
        [2] 7   
        [3] -1  

 [1]    {int[4]}

        [0] 0   
        [1] 1   
        [2] 7   
        [3] -1
 [2]    {int[4]}


        [0] 7   
        [1] 1   
        [2] 6   
        [3] -1

I have been trying to figure out how to do it but I did not manage to get it right.

If you could give me hand I would be grateful!

Many thanks!

Try:

var listB = new List<string>() { "4, 0, 7, -1,", "0, 1, 7, -1,", "7, 1, 6, -1," }
    .Select(
        x => x.TrimEnd(',') //removing last ","
                .Split(',') //splitting string into array by ","
                .Select(int.Parse) //parsing string to int
                .ToList()
    ).ToList();

It can be easily done with LINQ

var a = new List<string> {"1, 2, 3, 4", "5, 6, 7, 8"};

List<int[]> b = a.Select(s => s.Split(new [] {", "}, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray()).ToList();

Using LINQ is more succint but this is another way you could accomplish the same thing just separated out more.

var stringList = new List<string>() { "4, 0, 7, -1,", "0, 1, 7, -1,", "7, 1, 6, -1," };
        var intList = new List<int[]>();

        foreach(var str in stringList)
        {
            // Call Trim(',') to remove the trailing commas in your strings
            // Use Split(',') to split string into an array
            var splitStringArray = str.Trim(',').Split(',');

            // Use Parse() to convert the strings as integers and put them into a new int array
            var intArray = new int[]
            {
                int.Parse(splitStringArray[0])
                ,int.Parse(splitStringArray[1])
                ,int.Parse(splitStringArray[2])
                ,int.Parse(splitStringArray[3])
            };

            intList.Add(intArray);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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