读书人

找出table里面的重复行

发布时间: 2012-08-08 14:32:45 作者: rapoo

找到table里面的重复行
有一个DATATABLE DTA,里面的数据有重复,用DISTINCT 把 DTA里重复的数据去除,转成一个新的DATATABLE DTB,不知是否可用DTA-DTB这样的做法。

不能用for循环写法,数据量比较大,几万笔。dta的数据并不是从数据库里面查出来的,是从EXCEL汇进来的。

比如 dta
1 1 1
2 1 2
1 1 1
2 1 2
3 2 5
3 6 5
要得出dtb
1 1 1
2 1 2


[解决办法]

C# code
string[] distinctcols = new string[(DTA.Columns.Count)];foreach (DataColumn dc in DTA.Columns){   distinctcols[dc.Ordinal] = dc.ColumnName;}DataView mydataview = new DataView(DTA);DataTable DTB= mydataview.ToTable(true, distinctcols);
[解决办法]
C# code
        public static bool CheckReduplicated(DataTable dt, ref string strMsg, params string[] keyFields)        {            string f = "";            for (int i = 0; i < keyFields.Length; i++)            {                if (i != keyFields.Length - 1)                    f += keyFields[i] + ",";                else                    f += keyFields[i] + " ASC";            }            dt.DefaultView.Sort = f;            DataTable temp = dt.DefaultView.ToTable();            for (int i = 0; i < temp.Rows.Count; i++)            {                DataRow dr = temp.Rows[i];                if (i > 0)                {                    DataRow dr_pre = temp.Rows[i - 1];                    bool isReduplicated = true;                    foreach (string s in keyFields)                    {                        string value = dr[s].ToString();                        string value_pre = dr_pre[s].ToString();                        if (value != value_pre)                        {                            isReduplicated = false;                        }                    }                    if (isReduplicated)                    {                        if (strMsg.Length > 0)                        {                            strMsg += " ";                        }                        foreach (string s in keyFields)                        {                            strMsg += string.Format(@"[{0}:{1}]", s, dr[s].ToString());                        }                        strMsg += "有重复.";                        return true;                    }                }            }            return false;        } 

读书人网 >C#

热点推荐