Datacolumn to string array
I have one datacolumn and I have value in datacolumn like
"student1"
"student2"
"student3"
"student4"
I want them in one string like "student1,student2,student3,student4"
Can I convert datacolumn into string or string[] or List<string> without using for loop
Re: Datacolumn to string array
I think cast method may be useful for me but I don't know the way of passing parameter.
I used it with datacolumn and rows too
string[] s;
s = tblValue.Rows.Cast<typeof(string[])>();
string s;
s = tblValue.Rows.Cast<typeof(string)>();
but it gives some error messages
Re: Datacolumn to string array
First up, please provide your version when posting in future. If we don't know your version then we don't know that LINQ is an option.
Secondly, you can't cast DataRows as strings. They are not the same. You'd have to use a query to extract the values from the desired column into an enumerable object, convert that to an array and then join the elements of that array together into a single string:
Code:
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Rows.Add(1, "Peter");
table.Rows.Add(2, "Paul");
table.Rows.Add(3, "Mary");
var names = from DataRow row in table.Rows
select (string)row["Name"];
string[] arr = names.ToArray();
string str = string.Join(", ", arr);
Console.WriteLine(str);
Console.ReadLine();
}
}
}
That's the verbose version. Those three lines that create the string from the column values can be written as a single line like this:
Code:
string str = string.Join(", ", (from DataRow row in table.Rows
select (string)row["Name"]).ToArray());
Re: Datacolumn to string array
Happy new year VBForums.
Thank you very much. I got the way you are showing.
Actually I am using C# but got the solution.
Just tell me can we use dintinct and where keywords in Linq?
Re: Datacolumn to string array
Quote:
Originally Posted by ishrar
Actually I am using C# but got the solution.
That would explain why I provided C# code.
Quote:
Originally Posted by ishrar
Just tell me can we use dintinct and where keywords in Linq?
I just opened my MSDN Library and typed distinct into the index. The first result is for the Dictinct Clause and provides an explanation, a code example and various links, including to the Where Clause documentation. If I can do that, so can you.