我是编程的新手,所以这看起来有点简单,但我似乎无法弄明白。
我正在尝试查找值的一列中的数据表中的重复值。
以下是我试图做的事情。
DataRow[] dupresults = dt.Select("PROV_NEW");
TableIssues = string.Empty;
DataTable dtTemp = dt.DefaultView.ToTable(true, "NEW_PROV");
if (dupresults.Length == 0)
{
return true;
}
else
{
foreach (DataRow item in dupresults)
{
Console.WriteLine(item[1]);
TableIssues += "Provider Code is not unique for " + item[1].ToString() + ". Revise non-unique codes.\r\n\n\n\n";
}
return false;
}
好吧,但我也在搜索以确保PROV_NEW中没有空字段。所以我不知道该把它放在哪里。我对c#很新。我刚开始上周。我正在为我父亲的公司做项目。
private bool ValidateTable(DataSets.Setup.SETUP_MWPROVDataTable dt, out string TableIssues)
{
try
{
//NewCode not used for other row
DataRow[] result = dt.Select("PROV_NEW = ''");
DataRow[] dupresults = dt.Select("PROV_NEW");
TableIssues = string.Empty;
DataTable dtTemp = dt.DefaultView.ToTable(true, "NEW_PROV");
if (dupresults.Length == 0)
{
return true;
}
else
{
var duplicates = dt.AsEnumerable()
.Select(dr => dr.Field<string>("PROV_NEW"))
.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(g => g.Key)
.ToList();
foreach (DataRow item in dupresults)
{
Console.WriteLine(item[1]);
TableIssues += "Provider Code is not unique for " + item[1].ToString() + ". Revise non-unique codes.\r\n\n\n\n";
}
return false;
}
if (result.Length == 0)
{
//TODO: Add Next Step for validation
return true;
}
else
{
foreach (DataRow item in result)
{
Console.WriteLine(item[1]);
TableIssues += "Provider code " + item[1].ToString() + " is blank. Add new Provider code for " + item[1].ToString() +".\r\n\n\n";
}
return false;
}
}
catch (Exception)
{
throw;
}
}
}
答案 0 :(得分:13)
LINQ可以在这里为您提供帮助:
var duplicates = dt.AsEnumerable()
.Select(dr => dr.Field<string>("PROV_NEW"))
.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(g => g.Key)
.ToList();
// Now work with the set of duplicates
可替换地:
HashSet<string> providers = new HashSet<string>();
foreach (var provider in dt.AsEnumerable()
.Select(dr => dr.Field<string>("PROV_NEW")))
{
if (!providers.Add(provider))
{
// This provider is a duplicate
}
}
(这是有效的,因为如果值已经存在于集合中,HashSet<T>.Add
将返回false。)
答案 1 :(得分:2)
关于在多列选择中使用匿名类型LINQ的Jon Skeet's建议,我给自己一个解决方案,希望它也能帮到你:
DataTable dt_ = _data.Tables["MyTable"];
foreach (DataRow _dr in dt_.AsEnumerable()
.GroupBy(r => new
{
c1 = r.Field<string>("ColNAME1 of table dt_"),
c2 = r.Field<string>("ColNAME2 of table dt_"),
c3 = r.Field<string>("ColNAME3 of table dt_"),
...<any number of columns can be added>
}).Where(grp => grp.Count() > 1).SelectMany(itm => itm))
{
// Handle your Duplicate row entry
}
答案 2 :(得分:0)
dtEmp
是您工作的数据表
DataTable distinctTable = dtEmp.DefaultView.ToTable( /*distinct*/ true);