Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq query to check for duplicate values

In one of my pages I need to check if the entered information about a customer consists duplicate PAN NO,Email,Mobile No which may have been entered previously.Currently I am trying it using this Linq To SQL statement

    var duplicate = (from dup in dt.Data_Customer_Logs
                     where dup.cPanGirNo == panno 
                           || dup.cEmail == email 
                           || dup.nMobileNo.ToString() == mobno
    select dup).Any(); 

It is working but can anyone help me as to what is the correct method to solve my issue.Also if there are no records found what would be the result. Any suggestions are welcome.

like image 965
Priyank Patel Avatar asked Jun 19 '12 07:06

Priyank Patel


1 Answers

bool duplicateExists = dt.Data_Customer_Logs.Any(x => 
                         x.cPanGirNo == panno 
                      || x.cEmail == email
                      || x.nMobileNo.ToString() == mobno);

This is a tad cleaner if you just want to know if such records exist or not. And I think it will avoid bringing back multiple records to the client side and then doing IEnumerable<T>.Any on the results.

If you need to also get back the records that match the criteria, you can use IQueryable<T>.Where:

var duplicates =  dt.Data_Customer_Logs.Where(x => 
                         x.cPanGirNo == panno 
                      || x.cEmail == email
                      || x.nMobileNo.ToString() == mobno);
if(duplicates.Any())
{
    // use duplicates...
    foreach(var dup in duplicates)
    {
        //use dup.cEmail, dup.nMobileNo, etc.
like image 157
Eren Ersönmez Avatar answered Sep 29 '22 21:09

Eren Ersönmez