码迷,mamicode.com
首页 > 其他好文 > 详细

使用Linq 来解决Datatable 去除数据重复

时间:2015-10-10 21:21:32      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:

在这也说明下,除此之外还可以通过 DataView 的方式来处理,当个人觉得这有点不好用。这里就不多作说明了

代码比较简单,直接看代码

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace DTS
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable _dt = new DataTable();
            _dt.Columns.Add("id", typeof(int));
            _dt.Columns.Add("name", typeof(string));
            _dt.Columns.Add("address", typeof(string));

            DataRow _dr = _dt.NewRow();
            _dr["id"] = 1;
            _dr["name"] = "xiaodong";
            _dr["address"] = "beijing";
            _dt.Rows.Add(_dr);
            _dt.Rows.Add(_dr.ItemArray);
            _dt.Rows.Add(_dr.ItemArray);
            _dr = _dt.NewRow();

            _dr["id"] = 2;
            _dr["name"] = "xiaodong";
            _dr["address"] = "shanghai";
            _dt.Rows.Add(_dr);
            _dr = _dt.NewRow();


            _dr["id"] = 3;
            _dr["name"] = "xiaoming";
            _dr["address"] = "guangdong";
            _dt.Rows.Add(_dr);
            _dr = _dt.NewRow();

            _dr["id"] = 4;
            _dr["name"] = "xudaxia";
            _dr["address"] = "fujian";
            _dt.Rows.Add(_dr);
            _dt.Rows.Add(_dr.ItemArray);
            Console.WriteLine("--------------------原来有重复数据的Table----------------------");
            _dt.AsEnumerable().ToList().ForEach(
                m=>
                {
                    Console.WriteLine(m["id"].ToString() + "   " + m["name"].ToString() + "  " + m["address"].ToString());
                });

            Console.WriteLine("--------------------去除重复后的Table----------------------");
            var _comPresult = _dt.AsEnumerable().Distinct(new DataTableRowCompare());
            DataTable _resultDt = _comPresult.CopyToDataTable();

            _resultDt.AsEnumerable().ToList().ForEach(
               x =>
               {
                   Console.WriteLine(x["id"].ToString() + "    " + x["name"].ToString() + "   " + x["address"].ToString());
               });
            Console.Read();
        }
        public class DataTableRowCompare : IEqualityComparer<DataRow>
        {

            #region IEqualityComparer<DataRow> 成员

            public bool Equals(DataRow x, DataRow y)
            {
                return ((x.Field<int>("id") == y.Field<int>("id") && x.Field<string>("name") == y.Field<string>("name") && x.Field<string>("address") == y.Field<string>("address")));
            }

            public int GetHashCode(DataRow obj)
            {
                return obj.ToString().GetHashCode();
            }

            #endregion
        }

    }
}

 

使用Linq 来解决Datatable 去除数据重复

标签:

原文地址:http://www.cnblogs.com/byvar/p/4868138.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!