Ben
Ben

Reputation: 1153

C# Cannot convert from string [] to string

I have this method and get the above error on the line words.Add(rows); can anyone help? Thanks - Ben

private static IEnumerable<string> LoadWords(String filePath)
    {

        List<String> words = new List<String>();

        try
        {
            foreach (String line in File.ReadAllLines(filePath))
            {
                string[] rows = line.Split(',');

                words.Add(rows);
            }

        }
        catch (Exception e)
        {
            System.Windows.MessageBox.Show(e.Message);
        }

            return words;
    }

Upvotes: 1

Views: 6736

Answers (8)

Avi
Avi

Reputation: 251

u r trying to add string of array in a list of array

private static IEnumerable<string> LoadWords(String filePath)
    {

        List<String> words = new List<String>();

        try
        {
            foreach (String line in File.ReadAllLines(filePath))
            {
                string[] rows = line.Split(',');

                foreach(string str in rows)
                       words.Add(str);
            }

        }
        catch (Exception e)
        {
            System.Windows.MessageBox.Show(e.Message);
        }

            return words;
    }

Upvotes: 1

user153923
user153923

Reputation:

private static IEnumerable<string> LoadWords(String filePath)
{

    List<String> words = new List<String>();

    try
    {
        foreach (String line in File.ReadAllLines(filePath))
        {
            string[] rows = line.Split(',');

            foreach (String word in rows)
            {
                words.Add(word);
            }
        }

    }
    catch (Exception e)
    {
        System.Windows.MessageBox.Show(e.Message);
    }

        return words;
}

Upvotes: 0

iggymoran
iggymoran

Reputation: 4089

.Add will take another string, not an array of strings.

Try .AddRange instead.

Upvotes: 0

Adam Houldsworth
Adam Houldsworth

Reputation: 64487

You are trying to add a string array to a list that takes a string.

Try words.AddRange(rows);

Upvotes: 1

zs2020
zs2020

Reputation: 54524

Have a try of this:

words.AddRange(rows);

Upvotes: 0

Babak Naffas
Babak Naffas

Reputation: 12561

You are using the wrong method. You want the AddRange method.

words.AddRange(rows);

Upvotes: 0

Matthew Cox
Matthew Cox

Reputation: 13672

Change it to this

words.AddRange(rows);

You issue is that you are adding an array of items, not a single element.

You use AddRange() when adding a collection that implements System.Collections.Generic.IEnumerable<T>

See documentation here http://msdn.microsoft.com/en-us/library/z883w3dc.aspx

Upvotes: 4

BrokenGlass
BrokenGlass

Reputation: 160902

Instead of

words.Add(rows);

use this :

words.AddRange(rows);

rows is a string array containing multiple strings, so you have to add them with AddRange().

Upvotes: 6

Related Questions