Showing posts with label Linq. Show all posts
Showing posts with label Linq. Show all posts

Friday, August 07, 2015

DataTable row compare in C#

Here is the simple workaround to find the unique record from the source.
You must have two equal IEnumerable collection.

In Linq,we can use the "Except" method

In this example, I have 2 sample xml file that contains the records of books details such as book name,author and id.

In second XML has one new record, and wanted to output the new record in grid.

           DataSet ds = new DataSet();
            DataSet ds1 = new DataSet();
            ds.ReadXml(@"D:\Books.xml");


            bookgrd.DataSource = ds.Tables[0];
            bookgrd.DataBind();

            IEnumerable tbl1row = ds.Tables[0].AsEnumerable();
            ds1.ReadXml(@"D:\Books2.xml");


            
            IEnumerable tbl2row = ds1.Tables[0].AsEnumerable();
            GridView1.DataSource = ds1.Tables[0];
            GridView1.DataBind();
           
            var items = tbl2row.AsEnumerable().Select(r => r.Field("id"))
           .Except(tbl1row.AsEnumerable().Select(r => r.Field("id")));



            DataTable uniqueRow = (from row in tbl2row.AsEnumerable()
                                join id in items
                                on row.Field("id") equals id
                                select row).CopyToDataTable();

            GridView2.DataSource = uniqueRow;
            GridView2.DataBind();



Wednesday, December 22, 2010

Linq to class objects

This example shows how to use the array of class object and its variables on run time using "LINQ".
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class LinqClass
{
    public string Name;
    public string contact;
    public string city;

}

using System.Xml;
using System.Xml.Linq;
using System.Linq;
using System.Data;

var sp = new[] {
          new LinqClass { Name="Murugesan",
                          contact="9769104815",
                          city="Chennai"
                        },
                        new LinqClass { Name="Pandian",
                                        city="Madurai",
                                        contact="9786466642"
                                      }
          };
        foreach (var n in sp)
        { 
            Response.Write(n.Name.ToString());
        }