none
DataSet and LINQ Help Needed. RRS feed

  • Question

  • Hi I need some advice.  I am writing a program where an excel file gets imported and then stored to a dataset (that was easy), this DataSet is then applied to a datagrid for review purposes.  If everything looks good to the user then the imported information will be committed to the database(the not so easy part)  What I need to do is figure out a way to validate there isn't information in the imported file that is already in the database because this will cause duplicate data blah blah blah. 

    My problem is I can't decide how to go about this validation.  In addition, the validation only needs to occur on one column.  The question I pose to anyone who reads this is should I use LINQ to read over the DataSet & DataTable and then extract the information I need to validate with or is there some easier way and I am just making this way too hard?

    Any help would be great.

    Thanks,
    Nathan
    Thursday, May 21, 2009 2:02 PM

All replies

  • That is easy with Linq set operators IMHO. You can create a custom IEqualityComparer to define your equality on different rows and find out 'duplicates'. Here is a sample using L2S and the fantastic LinqPad (thanks to Mr.Joseph Albahari):

    void Main()
    {
    var usa =
      from p in Products.AsEnumerable()
      where p.OrderDetails.Any( od => 
                od.Order.Customer.Country == "USA" ) 
                && p.UnitPrice < 20
      orderby p.UnitPrice
      select p;
    var argentina =	
      from p in Products.AsEnumerable()
      where p.OrderDetails.Any( od => 
               od.Order.Customer.Country == "Argentina" ) 
               && p.UnitPrice < 20
      orderby p.UnitPrice
      select p;
    
    usa.Dump("USA customers bought");
    argentina.Dump("Argentina customers bought");
    
    IEnumerable<Products> result = 
      usa.Intersect( argentina, new myComparer() );
    	
    result.Dump("Equal unitprice accepted as a duplication");	
    }
    
    class myComparer : IEqualityComparer<Products>
    {
       public new bool Equals(Products x, Products y)
      {
         return x.UnitPrice == y.UnitPrice;
      }
    
      public int GetHashCode(Products p)
     {
         return p.UnitPrice.ToString().ToLower().GetHashCode();
     }
    }
    Thursday, May 21, 2009 5:43 PM