Linq查询以检查重复值

时间:2012-06-19 07:24:00

标签: c# asp.net linq-to-sql

在我的某个页面中,我需要检查输入的客户信息是否包含之前输入的重复PAN NO,Email,Mobile No。目前我正在尝试使用此Linq To SQL声明

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

它正在工作,但任何人都可以帮助我解决我的问题的正确方法。如果没有找到记录将会是什么结果。 欢迎任何建议。

2 个答案:

答案 0 :(得分:5)

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

如果你只是想知道这些记录是否存在,这是一个清洁工。而且我认为它会避免将多条记录带回客户端然后对结果进行IEnumerable<T>.Any

如果您还需要取回符合条件的记录,可以使用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.

答案 1 :(得分:2)

试试这个

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

if(duplicate != null && duplicate.Any())
   //here logic of what should happend if there is something in db