zoukankan      html  css  js  c++  java
  • C# Distinct去重DataTable

    • Source Data
    • 使用DataView去重
    • 使用Lambda表达式去重

    1. Source Data

    DataTable dtSource = new DataTable();
    dtSource.Columns.Add("UserID", System.Type.GetType("System.String"));
    dtSource.Columns.Add("UserName", System.Type.GetType("System.String"));
    dtSource.Columns.Add("Stage", System.Type.GetType("System.String"));
    DataRow dr = dtSource.NewRow();
    for (int i = 0; i < 2; i++)
    {
        dr[0] = "0000";
        dr[1] = "Lucky";
        dr[2] = "AA";
        dtSource.Rows.Add(dr.ItemArray);
    }
    dr[0] = "1111";
    dr[1] = "Poppy";
    dr[2] = "AB";
    dtSource.Rows.Add(dr.ItemArray);
    dr[0] = "2222";
    dr[1] = "Zack";
    dr[2] = "AC";
    dtSource.Rows.Add(dr.ItemArray);                
    

    2. 使用DataView去重

    DataView dv = dtSource.DefaultView;
    dv.Sort = "UserID ASC";
    DataTable distinctDT = dv.ToTable("NewData", true, new string[] { "UserID", "UserName", "Stage" });
    

    3. 使用Lambda表达式去重

    DataTable distinctDT = dtSource.Clone();
    var distinctRows = dtSource.AsEnumerable().Cast<DataRow>()
    					.Select(row => new
    					{
    						UserID = row.Field<string>("UserID"),
    						UserName = row.Field<string>("UserName"),
    						Stage = row.Field<string>("Stage"),
    					}).Distinct();
    if (distinctRows.ToList().Count > 0)
    {
    	distinctRows.ToList().ForEach(q =>
    	{
    		DataRow dr1 = distinctDT.NewRow();
    		dr1["UserID"] = q.UserID;
    		dr1["UserName"] = q.UserName;
    		dr1["Stage"] = q.Stage;
    		distinctDT.Rows.Add(dr1);
    	});
    }
    

  • 相关阅读:
    HDU 1013 Digital Roots
    HDU 1290 献给杭电五十周年校庆的礼物
    几何分割问题
    HDU 1222 Wolf and Rabbit
    HDU 1997 汉诺塔VII
    HDU 1443 Joseph
    HTML的标题样式
    HDU 1568 Fibonacci
    Hope
    HDU 1071 The area
  • 原文地址:https://www.cnblogs.com/LuckyZLi/p/12558802.html
Copyright © 2011-2022 走看看