Wednesday, 13 March 2013

Sample Linq program in C#

using System;
using System.Data;

class Program {
   public void DisplayProducts(DataTable table) {
       var productNames = from products in table.AsEnumerable() where products.Field<int>("ID") > 1 select products.Field<string>("ProductName");
       Console.WriteLine("Product Names: ");
       foreach (string productName in productNames)
       {
           Console.WriteLine(productName);
       }
       //DataRow[] test = table.Select("ID>" + 1);

       //foreach (DataRow productName in test)
       //{
       //    Console.WriteLine(productName["ProductName"]);
       //}
   }

   static void Main(string[] args) {
      DataTable table = new DataTable();
      table.Columns.Add("ID",typeof(Int32));
      table.Columns.Add("ProductName");

      table.Rows.Add(1, "Chai");
      table.Rows.Add(2, "Queso Cabrales");
      table.Rows.Add(3, "Tofu");
      table.Rows.Add(4, "Arjun");
      table.Rows.Add(5, "Kamal");
      table.Rows.Add(6, "Vijay");

      Program inst = new Program();
      inst.DisplayProducts(table);
      Console.ReadLine();
   }
}

No comments:

Post a Comment