📜  linq 数据表 - C# (1)

📅  最后修改于: 2023-12-03 15:02:41.587000             🧑  作者: Mango

Introduction to LINQ DataTables in C#

What is a LINQ DataTable?

A LINQ DataTable is a collection of data stored in a tabular format. It is similar to a database table but exists only in memory. It is an integral part of the Language Integrated Query (LINQ) that allows you to perform efficient and flexible data manipulation using C#.

Creating a LINQ DataTable

To create a LINQ DataTable in C#, you first need to add a reference to the System.Data.Linq namespace. Then you can create a new DataTable object and define its columns and data types. Here is an example of creating a simple LINQ DataTable:

using System.Data.Linq;

// create a new DataTable
DataTable customers = new DataTable("Customers");

// add columns to the DataTable
customers.Columns.Add("ID", typeof(int));
customers.Columns.Add("Name", typeof(string));
customers.Columns.Add("Email", typeof(string));

// add data to the DataTable
customers.Rows.Add(1, "John Smith", "jsmith@example.com");
customers.Rows.Add(2, "Jane Doe", "jdoe@example.com");
customers.Rows.Add(3, "Bob Johnson", "bjohnson@example.com");

In this example, we created a new LINQ DataTable called "Customers" with three columns: "ID", "Name", and "Email". We then added three rows of data to the table.

Querying a LINQ DataTable

One of the main benefits of a LINQ DataTable is the ability to query it using LINQ expressions. Here is an example of querying the "Customers" table created above to find all customers whose name starts with "J":

// query the DataTable
var results = from c in customers.AsEnumerable()
              where c.Field<string>("Name").StartsWith("J")
              select c;

// print out the results
foreach (var r in results)
{
    Console.WriteLine(r.Field<int>("ID") + " " + r.Field<string>("Name") + " " + r.Field<string>("Email"));
}

This LINQ expression selects all rows from the "Customers" table where the "Name" field starts with "J". The results are then printed out to the console.

Modifying a LINQ DataTable

Another important feature of a LINQ DataTable is the ability to modify its data. Here is an example of modifying the "Customers" table to update a customer's email address:

// find the customer to update
var customerToUpdate = customers.AsEnumerable().Where(c => c.Field<int>("ID") == 1).FirstOrDefault();

// update the email address
customerToUpdate.SetField("Email", "newemail@example.com");

This LINQ expression selects the customer with an ID of 1 and updates their email address. The SetField method is used to modify the value of the "Email" column.

Conclusion

In this introduction to LINQ DataTables in C#, we learned how to create, query, and modify a LINQ DataTable. With its flexible and efficient data manipulation capabilities, a LINQ DataTable is a powerful tool for any C# developer working with tabular data.