locked
Value from an array into a string RRS feed

  • Question

  • I'm trying to get the value from an array and put it into a string.  I know how to do this in VB, but having trouble with C#.

    void csvReader()
            {
                using (StreamReader readFile = new StreamReader("Joes.csv"))
                {
                    string line;
                    string[] row;
                    List<string[]> parsedData = new List<string[]>();
                    while ((line = readFile.ReadLine()) != null)
                    {
                        row = line.Split(',');
                        parsedData.Add(row);
                    }
                }
            }
    so what I'm trying to do is get a value from parsedData and put it into a string.  Now in VB it would be something along the lines of strTest = parsedData(1) to get the value from the second cell in the array and put it into strTest.  Looking to do something similar to that.  When I try that in C# I get Error   'parsedData' is a 'variable' but is used like a 'method'. 
    I'm sure it has something to do with the list I'm using but I'm not sure how to do the other part differently.
    Tuesday, March 16, 2010 6:08 PM

Answers

  • parsedData is a list of arrays of strings, not a list of strings, so each element will be an array of strings.

    You can try:

    string text = parsedData [0][1]; // first line, second element

    HTH
    --mc

    • Marked as answer by temlehdrol Tuesday, March 16, 2010 6:24 PM
    Tuesday, March 16, 2010 6:22 PM

All replies

  • in C# you use []  instead of () .. try it.
    Tuesday, March 16, 2010 6:11 PM
  • with that I get the following:  Cannot implicitly convert type 'string[]' to 'string'   

    now that I wrote that down I remember that is how I first tried it, sorry for not including that earlier...

    Tuesday, March 16, 2010 6:19 PM
  • parsedData is a list of arrays of strings, not a list of strings, so each element will be an array of strings.

    You can try:

    string text = parsedData [0][1]; // first line, second element

    HTH
    --mc

    • Marked as answer by temlehdrol Tuesday, March 16, 2010 6:24 PM
    Tuesday, March 16, 2010 6:22 PM
  • Could c


    Could you paste that piece of code also.  if you are trying something like

    string newString = parsedData[0]

    then it will fail. As parsedData is a list of (String Array) and not simple strings.

    So it will not be  able to convert string[]  to string.
    Tuesday, March 16, 2010 6:27 PM
  • I knew it was something stupid that I was missing. 
    Now if I was to have lets say 2 rows, I could use y for the row variable and x for the col variable correct and it would go to the corresponding row/col in the array?
    y = 1;
    x = 2;
    strText = parsedData[y][x];

    Would be line 2 col 3 right?
    Tuesday, March 16, 2010 6:27 PM
  • Yes, in C# collections are zero-based.

    HTH
    --mc
    Tuesday, March 16, 2010 10:57 PM