2017-05-08 52 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(); 

     }