2017-05-08 51 views
1

数据表副本是否有可能从基于某一特定领域的数据表和条件C#去除根据现场和条件

一样,如果我有以下的记录中删除重复项:

名称:阿里

appointment_type:牙科

appointment_date:2017年8月5日08:00:00

名称:阿里

appointment_type:牙科

appointment_date:2017年8月5日16:00:00

从上面的例子中,患者阿里有两个约会,我想删除后任命(S)(这是对2017年8月5日16:00:00)

换句话说

, 去除病人的“阿里”的所有约会,并保持国内最早唯一

是有可能做到这一点的LINQ?

+0

首先在一个Where中过滤它们,然后如下所述应用RemoveRange:http://stackoverflow.com/questions/14746783/remove-all-but-the-first-item-in-a-list –

回答

1

您可能想要GroupBy项目,然后OrderBy每个组基于AppointmentDate,从每个组只取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(); 
+0

谢谢!它工作完美 –

+0

不客气.. :) – Ian

0

尝试以下操作:

 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(); 

     }