C# - Remove rows with the same column value from a DataTable

前端 未结 6 698
深忆病人
深忆病人 2021-01-03 09:40

I have a DataTable which looks like this:

 ID   Name    DateBirth
.......................
 1     aa      1.1.11
 2     bb      2.3.11
 2     cc          


        
6条回答
  •  说谎
    说谎 (楼主)
    2021-01-03 10:21

    Heres a way to achive this, All you need to use moreLinq library use its function DistinctBy

    Code:

    protected void Page_Load(object sender, EventArgs e)
    {
      var DistinctByIdColumn = getDT2().AsEnumerable()
                                       .DistinctBy(
                                       row => new { Id = row["Id"] });
      DataTable dtDistinctByIdColumn = DistinctByIdColumn.CopyToDataTable();
    }
    
    
    public DataTable getDT2()
    {
       DataTable dt = new DataTable();
       dt.Columns.Add("Id", typeof(string));
       dt.Columns.Add("Name", typeof(string));
       dt.Columns.Add("Dob", typeof(string));
       dt.Rows.Add("1", "aa","1.1.11");
       dt.Rows.Add("2", "bb","2.3.11");
       dt.Rows.Add("2", "cc","1.2.12");
       dt.Rows.Add("3", "cd","2.3.12");
       return dt;
    }
    

    OutPut: As what you expected

    enter image description here

    For moreLinq sample code view my blog

提交回复
热议问题