简体   繁体   English

如何在C#中使用LINQ从sql数据库中找到重复项

[英]How to find duplicates from sql database using LINQ in c#

I have a method which will return duplicate records from database using sql command. 我有一个方法将使用sql命令从数据库返回重复记录。 The code is: 代码是:

 public bool RecordExists(string name)
   {
       OleDbCommand cmd = new OleDbCommand("select count(*) from Demographics where thal_Id = '" + txtPtntSmpl.Text + "'", con);
       int recordCount = Convert.ToInt32(cmd.ExecuteScalar());
       cn.Close();
       return recordCount > 0;
   } 

According to this ,If I call this method in textbox leave event I will raise an error while duplicate records occurs from database. 据此,如果我在文本框离开事件中调用此方法,则当数据库中出现重复记录时,我将引发一个错误。 Now I want the same operation by using linq . 现在我想要使用linq进行相同的操作 Please anyone help me. 请任何人帮助我。 Thanking you 感谢您

Assuming you have a List of Demographic and you want to see how many match a certain text value, try something like this: 假设您有一个受众特征列表,并且想要查看有多少匹配某个文本值,请尝试执行以下操作:

 public bool RecordExists(string name)
   {
       List<Demographic> demographics = PopulateList();

       return demographics.Count(d => d.thal_Id == name) > 0;
   } 

If you use Linq to SQL, having dc as your data context, it should look smth like this: 如果您使用Linq to SQL,并以dc作为数据上下文,则其外观应如下所示:

public bool RecordExists(string id)
{
    return dc.Demographics.Any(d => d.thal_Id == id);
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM