【问题标题】:C# remove datatable duplicates based on field and conditionC# 根据字段和条件删除数据表重复项
【发布时间】:2017-05-08 07:41:57
【问题描述】:

是否可以根据特定字段和条件从数据表中删除重复项

如果我有以下记录:

姓名:阿里

约会类型:牙科

约会日期:2017 年 8 月 5 日 08:00:00

姓名:阿里

约会类型:牙科

约会日期:2017 年 8 月 5 日 16:00:00

从上面的例子中,病人阿里有两个约会,我想删除后面的约会(2017 年 8 月 5 日 16:00:00)

换句话说, 删除病人“阿里”的所有预约,只保留最早的预约

在 LINQ 中可以做到吗?

【问题讨论】:

标签: c# linq


【解决方案1】:

您可能希望GroupBy 项目,然后基于AppointmentDate 的每个组OrderBy,只从每个组中获取First(最早的)。结果将仅是最早的约会:

List<Patient> patients = new List<Patient>(); //change this with your actual list/IEnumerable

IEnumerable<Patient> earliestAppointmentRecorded = patients.GroupBy(x => x.Name.ToLower().Trim())
   .Select(x => x.OrderBy(y => y.AppointmentDate).First());

假设class 如下:

public class Patient {
  public string Name { get; set; }
  public string AppointmentType { get; set; }
  public DateTime AppointmentDate { get; set; }

};

并且,假设您想用 earliestAppointmentRecorded 的记录替换较早的记录,您可以这样做:

patients = earliestAppointmentRecorded.ToList();

【讨论】:

    【解决方案2】:

    尝试以下:

            static void Main(string[] args)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("name", typeof(string));
                dt.Columns.Add("appointment_type", typeof(string));
                dt.Columns.Add("appointment_date", typeof(DateTime));
    
                dt.Rows.Add(new object[] { "Ali", "dental", DateTime.Parse("8/5/2017 08:00:00")});
                dt.Rows.Add(new object[] { "Ali", "dental", DateTime.Parse("8/5/2017 16:00:00")});
    
                var groups = dt.AsEnumerable().GroupBy(x => new { name = x.Field<string>("name"), type = x.Field<string>("appointment_type") }).ToList();
    
                dt = groups.Select(x => x.OrderBy(y => y.Field<DateTime>("appointment_date")).LastOrDefault()).CopyToDataTable();
    
            }
    

    【讨论】:

      猜你喜欢
      • 2020-02-17
      • 1970-01-01
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      • 2014-03-14
      • 1970-01-01
      相关资源
      最近更新 更多