0

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!

1
  • So separate this into different parts - for example, splitting the string by commas, and converting each substring into an int. How far have you got with that? Commented Nov 25, 2014 at 14:01

3 Answers 3

1

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();
Sign up to request clarification or add additional context in comments.

Comments

0

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);
        }

Comments

0

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();

1 Comment

Thanks for your answer! Just one thing, how could I get rid of the commas?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.