.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> LINQ >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Use LINQ with DataTable

Posted By:Syed Shakeer Hussain       Posted Date: December 17, 2011    Points: 40    Category: LINQ    URL: http://www.dotnetspark.com  

In this article you can learn how to return Mulitple Column records and using WHERE Condition on DataTable using LINQ
 

Code sample

using LINQ
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

using System.Data;
using System.Data.SqlClient;


namespace LinQSamples
{
    class Program
    {
        static void Main(string[] args)
        {

           DtMethod();

         }      

        public static DataTable  createDataTable()
        {         
            DataTable dt = new DataTable();
            dt.Columns.Add("empid", typeof(int));
            dt.Columns.Add("empname", typeof(string));
            dt.Columns.Add("salary", typeof(int));
            dt.Rows.Add(100, "Shakeer Hussain", 10000);
            dt.Rows.Add(101, "Shakeer", 1000);
            dt.Rows.Add(102, "Hussain", 3000);
            dt.Rows.Add(103, "Syed Shakeer Hussain", 66000);
            dt.Rows.Add(104, "diamond", 5000);
            dt.Rows.Add(105, "AABBCC", 100);
            dt.Rows.Add(106, "XXYYZZ", 4500);
            dt.Rows.Add(107, "MMKKLL", 7000);
            return dt;
        }

  public static void DtMethod()
  {
  DataTable dtTable = createDataTable();
///SELECT Statement using LINQ
var SelectQuery = from sq in dtTable.AsEnumerable() select sq;
 
Console.WriteLine("\nSelect statement");
Console.WriteLine("-------------------");
 
foreach (DataRow Query in SelectQuery)
{
Console.WriteLine("{0}\t{1}\t{2}", Query.ItemArray);
 }

 
      ///Select Statement with where condition(empid =100)    
    var querySalarySum = from qs in dtTable.AsEnumerable()
                             where qs.Field("empid") == 100
                             select qs;

    Console.WriteLine("EmpId \t Name \t\t Salary");

foreach (DataRow dr in querySalarySum)
{
     Console.WriteLine("{0}\t{1}\t{2}",
                       dr.Field("empid"),
                       dr.Field("empname"),
 
                       dr.Field("salary"));
}

       }

  }

}


     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend