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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-04-25 11:00:00 +0000
Seen: 15 times
Last updated: Oct 04 '21