Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To choose a specific column from a DataTable using LINQ, you can use the Select method with a lambda expression that specifies the column you want.

Here's an example code snippet:

DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(1, "John");
dt.Rows.Add(2, "Jane");

// Choose the "Name" column using LINQ
var names = dt.AsEnumerable().Select(row => row.Field<string>("Name"));

// Display the names
foreach (var name in names)
{
    Console.WriteLine(name);
}

In this example, we create a DataTable with two columns (ID and Name) and two rows of data. Then, we use LINQ to select only the "Name" column from the DataTable and store the results in a variable called "names". Finally, we loop through the names and print them to the console.