这是我第一次使用Datarows或表格数据。考虑到我有一个包含两列的简单表,一个包含ID,另一个包含名称字符串。我需要做的是找到两个具有相同ID的Datarows,并将这两行传递给另一个函数,我们称之为HandleTheDuplicates
。
目前我正在尝试将之前的ID存储在另一个变量中并检查它是否与当前ID匹配,然后将其添加到DataRow类型的列表中。
List<DataRow> RowList = new List<DataRow>();
int previous = 0 ;
foreach (DataRow rowToMatch in importSetOfTables.Tables["MyTable"].Rows)
{
int rowID = Convert.ToInt32(rowToMatch["ID"]);
if (previous == rowID)
{
RowList.Add(rowToMatch);
}
else
{
RowList.Clear();
}
previous = rowID;
if(RowList.Count > 1) //in case of a match
{
HandleTheDuplicates(RowList);
}
}
我不知道这是否是做这样的事情的正确方法,或者是否有更简单的事情。
答案 0 :(得分:1)
LINQ是一个不错的选择:
sudo chmod 755 /usr/local/lib
如果你想从原始集合中删除它们,另一个foreach循环可能会起作用:(通常不想从正在迭代的集合中删除项目)
List<DataRow> RowList = new List<DataRow>();
foreach (DataRow row in importSetOfTables.Tables["MyTable"].Rows)
{
// Use LINQ to get a list of rows matching on ID
List<DataRow> matches = (from t in importSetOfTables.Tables["MyTable"].Rows
where row.ID == t.ID
select a).ToList();
// Insert matching rows into your collection
if (matches.Count() > 0 )
if (!(RowList.Contains(matches[0]))
RowList.AddRange(matches);
}
答案 1 :(得分:1)
如果您按照ID排序DataTable,那么您的代码可以正常工作。确保在ID字段上设置DataTable.DefaultView.Sort
属性,然后使用DataTable.DefaultView创建循环
List<DataRow> RowList = new List<DataRow>();
int previous = 0 ;
importSetOfTables.Tables["MyTable"].DefaultView.Sort = "ID";
foreach (DataRowView rw in importSetOfTables.Tables["MyTable"].DefaultView)
{
int rowID = Convert.ToInt32(rw["ID"]);
if (previous == rowID)
RowList.Add(rw.Row);
else
{
// Call the function that handles the duplicates
if(RowList.Count > 1)
HandleTheDuplicates(RowList);
RowList.Clear();
}
previous = rowID;
}