locked
problem building a string with StringBuilder and string.Join and some Linq -- how to fix? RRS feed

  • Question

  • I want to build a string from a dataTable using StringBuilder (using VS 2008) -- the goal is to write this string to a text file.  Here is what I am trying, but I get the error

    1) The best overloaded method match for 'string.Join(string, string[])' has some invalid arguments
    2) Argument '2': cannot convert from 'System.Collections.Generic.IEnumerable<string>' to 'string[]'

    --and here is the string I am trying to build (using some Linq)

    var stringBuilder = new StringBuilder();  //--1st row contains column headers

    stringBuilder.AppendLine(string.Join("\t", dataTable.Columns.Cast<DataColumn>().Select(arg => arg.ColumnName)));  //--this is the first row

    I tried adding .ToString()  in various locations of arg2 but still did not fix the problem(s).  Any suggestions appreciated how I could get this to work.

    Thanks


    Rich P



    • Edited by Rich P123 Wednesday, May 22, 2013 4:24 PM
    Wednesday, May 22, 2013 4:21 PM

Answers

  • As the error you're getting says, there is no overload for "string.Join" that accepts an "IEnumerable<string>".  There is only one that accepts a "string[]".

    There was an additional overload added in .NET 4.0 that accepts an "IEnumerable<string>", which is potentially the cause of your confusion.

    Add a "ToArray()" call to convert the sequence into an array.

    • Marked as answer by Rich P123 Wednesday, May 22, 2013 4:42 PM
    Wednesday, May 22, 2013 4:27 PM

All replies

  • As the error you're getting says, there is no overload for "string.Join" that accepts an "IEnumerable<string>".  There is only one that accepts a "string[]".

    There was an additional overload added in .NET 4.0 that accepts an "IEnumerable<string>", which is potentially the cause of your confusion.

    Add a "ToArray()" call to convert the sequence into an array.

    • Marked as answer by Rich P123 Wednesday, May 22, 2013 4:42 PM
    Wednesday, May 22, 2013 4:27 PM
  • Yay!  It made the red go away -- yay!  :)  Here's the whole procedure -- with the .ToArray()

    private string GetTextFromDataTable(DataTable dataTable)
    {
       var stringBuilder = new StringBuilder();
       stringBuilder.AppendLine(string.Join("\t", dataTable.Columns.Cast<DataColumn>().Select(arg => arg.ColumnName).ToArray()));
       foreach (DataRow dataRow in dataTable.Rows)
          stringBuilder.AppendLine(string.Join("\t", dataRow.ItemArray.Select(arg => arg.ToString()).ToArray()));                  

       return stringBuilder.ToString();
    }


    Rich P

    Wednesday, May 22, 2013 4:42 PM