Ask Your Question
3

How can you use linq to choose a specific column from a datatable?

asked 2022-04-25 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-10-04 16:00:00 +0000

djk gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2022-04-25 11:00:00 +0000

Seen: 15 times

Last updated: Oct 04 '21