使用for循环进行datagrid搜索并总结重复列

时间:2013-07-25 01:36:22

标签: c# .net for-loop datagridview

This is a sample data shown in my datagrid


如何在c#中完成?只是为这个寻找任何建议..?

1 个答案:

答案 0 :(得分:0)

考虑到您的照片代表您创建的网格,
调用此方法来查找重复项:

/// <summary>
/// Finds the duplicates inside of a DataGridView
/// </summary>
/// <param name="grid">The instance of the DataGridView</param>
/// <param name="columnNamesToCompare">Collection of the Column.Name to compare</param>
/// <returns>List of KeyValuePairs of the index and list of it's duplicates</returns>
public static IEnumerable<KeyValuePair<int, List<int>>> FindDuplicates(this DataGridView grid, ICollection<string> columnNamesToCompare) {
        var dupesLog = new List<int>(); //represents rows that were marked as duplicates
        var locDupes = new List<int>(); //collector for the yield return
        for (int i = 0; i < grid.Rows.Count; i++) {
            if (dupesLog.Contains(i)) continue;
            locDupes.Clear();
            for (int j = 0; j < grid.Rows.Count; j++) {
                if (j==i) continue;
                foreach (string column in columnNamesToCompare) {
                    if (grid.Rows[i].Cells[column].Value.Equals(grid.Rows[j].Cells[column].Value) == false)
                        goto _next;
                }
                //if it got to here, means it is true
                locDupes.Add(j);
                dupesLog.Add(j);
                _next:
                continue;
            }
            if (locDupes.Count > 0)
                yield return new KeyValuePair<int, List<int>>(i, locDupes);
        }
    }

可以有更有效的方法来做到这一点,但这就是我本来会做到的 我没有测试它,但试一试。