我在 DataTable 中有 3 列
ID 名称计数
1詹姆斯4345
2 克里斯汀 89231
3詹姆斯599
4 苏尼尔 317113
我需要第 1 行和第 3 行消失,新的数据表只返回第 2 行和第 4 行。我在关于 SO- this guy的建议中发现了一个非常好的相关问题。但是他的解决方案使用哈希表,并且只删除了第 3 行,而不是第 1 行和第 3 行。救命!
我在 DataTable 中有 3 列
ID 名称计数
1詹姆斯4345
2 克里斯汀 89231
3詹姆斯599
4 苏尼尔 317113
我需要第 1 行和第 3 行消失,新的数据表只返回第 2 行和第 4 行。我在关于 SO- this guy的建议中发现了一个非常好的相关问题。但是他的解决方案使用哈希表,并且只删除了第 3 行,而不是第 1 行和第 3 行。救命!
我试过这个从数据表中删除重复项..
using System.Data;
using System.Linq;
...
//assuming 'ds' is your DataSet
//and that ds has only one DataTable, therefore that table's index is '0'
DataTable dt = ds.Tables[0];
DataView dv = new DataView(dt);
string cols = string.Empty;
foreach (DataColumn col in dt.Columns)
{
if (!string.IsNullOrEmpty(cols)) cols += ",";
cols += col.ColumnName;
}
dt = dv.ToTable(true, cols.Split(','));
ds.Tables.RemoveAt(0);
ds.Tables.Add(dt);
以下单行代码将避免重复的行。
ds.Tables["Employee"].DefaultView.ToTable(true,"Name");
ds——数据集对象
dt.DefaultView.ToTable( true, "Name");
dt – 数据表对象
像这样的东西怎么样;
伪代码:假设对象有 3 个属性:[Id, Name, Value] 并且被称为 NameObjects 并且是 IEnumerable(List NameObjects;)
var _newNameObjectList = new List<NameObject>();
foreach(var nameObject in NameObjecs)
{
if(_newNameObjectList.Select(x => x.Name == nameObject.Name).ToList().Count > 0)
{
_newNameObjectList.RemoveAll(x => x.Name == nameObject.Name);
continue;
}
else
{
_newNameObjectList.Add(nameObject);
}
}
这应该有效。这使用命名空间 System.Linq;
好的,所以我查看了 Pandiya 向我指出的博客。在评论部分,一个名叫 Kevin Morris 的小伙子发布了一个使用 C# 字典的解决方案,它对我有用。
在我的主要部分中,我写道:
string keyColumn = "Website";
RemoveDuplicates(table1, keyColumn);
我的 RemoveDuplicates 函数定义为:
private void RemoveDuplicates(DataTable table1, string keyColumn)
{
Dictionary<string, string> uniquenessDict = new Dictionary<string, string>(table1.Rows.Count);
StringBuilder sb = null;
int rowIndex = 0;
DataRow row;
DataRowCollection rows = table1.Rows;
while (rowIndex < rows.Count - 1)
{
row = rows[rowIndex];
sb = new StringBuilder();
sb.Append(((string)row[keyColumn]));
if (uniquenessDict.ContainsKey(sb.ToString()))
{
rows.Remove(row);
if (RemoveAllDupes)
{
row = rows[rowIndex - 1];
rows.Remove(row);
}
}
else
{
uniquenessDict.Add(sb.ToString(), string.Empty);
rowIndex++;
}
}
}
如果你去博客,你会发现一个更通用的函数,它允许在多个列上嗅探欺骗。我添加了一个标志——RemoveAllDupes——以防我想删除所有重复的行,但这仍然假设这些行是按名称排序的,并且只涉及重复而不涉及三次、三次等。如果有人可以,请更新此代码以反映删除此类代码。