Shrey
Shrey

Reputation: 63

How to add "String[] or List<String>" as ONE cell entry in a DataTable in C#?

I am trying to create a datatable containing cells with lines > 1. (FYI: new to C#, doesn't know anything about OOPS...Please be kind) This is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.IO;
namespace Excelapp
{
class Program
{
    static void Main(string[] args)
    {
        DataTable table = new DataTable();
        table.Columns.Add("LOCarray",typeof(String[]));
        table.Columns.Add("LOCstring", typeof(String));
        table.Columns.Add("LOClist", typeof(List<String>));


        String[] LOCarray = new String[2] {"Line1","Line2" };
        String LOCstring = "Line1\n\rLine2";
        List<String> LOClist = new List<String>();
        LOClist.Add("Line1");
        LOClist.Add("Line2");

        table.Rows.Add(LOCarray, LOCstring, LOClist);

        }
    }
}

Output is:

DataSet Visualizer enter image description here

As you can see, This is not what I want. Even when I am writing as String it is not showing \n character.

Please help me.

Upvotes: 2

Views: 1736

Answers (2)

Cameron
Cameron

Reputation: 2594

Another solution if you prefer Linq is to use the Aggregate function.

Example:

IEnumerable<string> collection = new List<string>() { "This", "is", "a", "sentence", "."};

var sentence = collection.Aggregate((a, b) => a + " " + b);

Or in your case, it'd be

var myValue = locList.Aggregate((a, b) => a + "\n\r" + b);

Upvotes: 0

mybirthname
mybirthname

Reputation: 18127

string[] arr = { "one", "two", "three" };

string arrayValuesWithNewLineSep = string.Join("\n", arr));

Upvotes: 3

Related Questions