LINQ to DataSet (C#)

LINQ to DataSet

  • Perform set operations on sequences of DataRow objects.
  • Retrieve and set DataColumn values
  • Obtain a LINQ standard IEnumerable sequence from a DataTable so Standard Query Operatorsmay be called.


To use LINQ to Dataset include next namespaces

  1. using System.Data; using System.Linq;

Step by Step Exemple:

Starting with a simple class:

  1. class Student {
  2.       public int Id;
  3.       public string Name;
  4.  }

this class is like a table where we have an row Id (public int Id) and a value (here is Name public string Name)

Next convert a list of Student Class in a Data Table

  1.     // create DataTable
  2.       DataTable table = new DataTable();
  3.       table.Columns.Add("Id", typeof(Int32));
  4.       table.Columns.Add("Name", typeof(string));
  5.          // fill with info
  6.      foreach (Student student in students){
  7.           table.Rows.Add(student.Id, student.Name);
  8.      }

Other Query examples:

There are to way of write a LINQ Query
Query expression
and
Method Query

  1. // Query expression example
  2. var query = from r in customerDataTable.AsEnumerable()
  3.      where r.Field("LastName") == "Smith"
  4.      select r.Field(“FirstName”);
  1. // same example in Method query
  2. var query = customerDataTable.AsEnumerable()
  3.             .Where(dr => dr.Field("LastName") == "Smith")
  4.             .Select(dr => dr.Field("FirstName"));

Buy Visual studio:

Comments are closed.