[c#] How to Convert the value in DataTable into a string array in c#

I have a DataTable that contains a single row. I want to convert this DataTable values into a string array such that i can access the column values of that DataTable through the string array index For example, if my DataTable is as follows

|  Name  |  Address  |   Age  |
-------------------------------
|  jim   |    USA    |   23   |

I want to store the values in that Datatable into my string array such that MyStringArray[1] will give me the value USA.

Thanks in Advance

This question is related to c# .net linq

The answer is


If you would like to use System.Data instead of System.LINQ, then you can do something like this.

 List<string> BrandsInDataTable = new List<string>();
 DataTable g = Access._ME_G_BrandsInPop(); 
        if (g.Rows.Count > 0)
        {
            for (int x = 0; x < g.Rows.Count; x++)
                BrandsInDataTable.Add(g.Rows[x]["Name"].ToString()); 
        }
        else return;

Perhaps something like this, assuming that there are many of these rows inside of the datatable and that each row is row:

List<string[]> MyStringArrays = new List<string[]>();
foreach( var row in datatable.rows )//or similar
{
 MyStringArrays.Add( new string[]{row.Name,row.Address,row.Age.ToString()} );
}

You could then access one:

MyStringArrays.ElementAt(0)[1]

If you use linqpad, here is a very simple scenario of your example:

class Datatable
{
 public List<data> rows { get; set; }
 public Datatable(){
  rows = new List<data>();
 }
}

class data
{
 public string Name { get; set; }
 public string Address { get; set; }
 public int Age { get; set; }
}

void Main()
{
 var datatable = new Datatable();
 var r = new data();
 r.Name = "Jim";
 r.Address = "USA";
 r.Age = 23;
 datatable.rows.Add(r);
 List<string[]> MyStringArrays = new List<string[]>();
 foreach( var row in datatable.rows )//or similar
 {
  MyStringArrays.Add( new string[]{row.Name,row.Address,row.Age.ToString()} );
 }
 var s = MyStringArrays.ElementAt(0)[1];
 Console.Write(s);//"USA"
}

    private string[] GetPrimaryKeysofTable(string TableName)
    {
        string stsqlCommand = "SELECT column_name FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE " +
                              "WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1" +
                              "AND table_name = '" +TableName+ "'";
        SqlCommand command = new SqlCommand(stsqlCommand, Connection);
        SqlDataAdapter adapter = new SqlDataAdapter();
        adapter.SelectCommand = command;

        DataTable table = new DataTable();
        table.Locale = System.Globalization.CultureInfo.InvariantCulture;

        adapter.Fill(table);

        string[] result = new string[table.Rows.Count];
        int i = 0;
        foreach (DataRow dr in table.Rows)
        {
            result[i++] = dr[0].ToString();
        }

        return result;
    }

 
            string[] result = new string[table.Columns.Count];
            DataRow dr = table.Rows[0];
            for (int i = 0; i < dr.ItemArray.Length; i++)
            {
                result[i] = dr[i].ToString();
            }
            foreach (string str in result)
                Console.WriteLine(str);


If that's all what you want to do, you don't need to convert it into an array. You can just access it as:

string myData=yourDataTable.Rows[0][1].ToString();//Gives you USA

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to linq

Async await in linq select How to resolve Value cannot be null. Parameter name: source in linq? What does Include() do in LINQ? Selecting multiple columns with linq query and lambda expression System.Collections.Generic.List does not contain a definition for 'Select' lambda expression join multiple tables with select and where clause LINQ select one field from list of DTO objects to array The model backing the 'ApplicationDbContext' context has changed since the database was created Check if two lists are equal Why is this error, 'Sequence contains no elements', happening?