使用C#在数据表中重复检查行

时间:2012-12-15 11:48:05

标签: c#-4.0

我有如下数据表。这里不允许排2,3,4,5。我如何使用C#验证此方案。请帮忙。这里的列数不固定。


  A             B             C
  A             B             C
  A             B             
  A                           C
                B             C
  A             B             B
  B             B             C
  A             C             B

1 个答案:

答案 0 :(得分:1)

C#with LinQ

此函数可消除列中的重复项和空值。如果不是您想要的null,那么您只需要根据需要更改“DBNull”。

public static DataTable FilterDataTable(DataTable table) 
    {
        // Erase duplicates
        DataView dv = new DataView(table);
        table = dv.ToTable(true, table.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray()); 

        // Get Null values
        List<DataRow> toErase = new List<DataRow>();
        foreach (DataRow item in table.Rows)            
            for (int i = 0; i < item.ItemArray.Length; i++)
            {
                if (item.ItemArray[i].GetType().Name == "DBNull")
                { toErase.Add(item); break; }

            }            
        //Erase Null Values
        foreach (DataRow item in toErase)            
            table.Rows.Remove(item);

        return table;            
    }