方法一:ToTable方法
public static bool IsDistinct(DataTable dt, params string[] columns)
{
DataView dv = new DataView(dt);
var distinctTable = dv.ToTable(true, columns);
if (!distinctTable.Rows.Count.Equals(dt.Rows.Count))
return true;
return false;
}
方法二:分组统计
public static bool IsDistinct(DataTable dt)
{
var sList = dt.AsEnumerable()
.GroupBy
(g => new { NAME= g["NAME"].ToString() })
.Select(S => new { NAME= S.Key.NAME, Count = S.Count() }).ToList();
if (sList.Count(c => c.Count > 1) > 0)
{
return true;
}
return false;
}
输出==>
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("NAME", typeof(string));
dt.Columns.Add("AGE", typeof(int));
Random rd = new Random();
for (int i = 0; i < 20; i++)
{
var newRow = dt.NewRow();
newRow["ID"] = i;
newRow["NAME"] = "czj" + i;
newRow["AGE"] = rd.Next(1, 70);
dt.Rows.Add(newRow);
}
var newRowSecond = dt.NewRow();
newRowSecond["ID"] = "1000";
newRowSecond["NAME"] = "czj10";
newRowSecond["AGE"] = rd.Next(1, 70);
dt.Rows.Add(newRowSecond);
var result = IsDistinct(dt, "ID", "NAME");//false
result = IsDistinct(dt, "NAME");//true
result = IsDistinct(dt, "AGE");//false/true
var result1 = IsDistinct(dt);//true