简体   繁体   中英

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 在此处输入图片说明

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM