C#根据字段和条件删除重复的数据表

C#根据字段和条件删除重复的数据表,c#,linq,C#,Linq,是否可以根据特定字段和条件从数据表中删除重复项 如果我有以下记录: 姓名:阿里 预约类型:牙科 预约日期:2017年8月5日08:00:00 姓名:阿里 预约类型:牙科 预约日期:2017年8月5日16:00:00 从上面的例子中,患者Ali有两次预约,我想取消之后的预约(2017年8月5日16:00:00) 换句话说,, 取消患者“Ali”的所有预约,仅保留最早的预约 是否可以在LINQ中执行此操作?您可能希望根据项目进行分组,然后根据任命日期对每组进行排序,只取每组中的第一个(最早的)。结果

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

如果我有以下记录:

姓名:阿里

预约类型:牙科

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

姓名:阿里

预约类型:牙科

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

从上面的例子中,患者Ali有两次预约,我想取消之后的预约(2017年8月5日16:00:00)

换句话说,, 取消患者“Ali”的所有预约,仅保留最早的预约


是否可以在LINQ中执行此操作?

您可能希望根据项目进行分组,然后根据任命日期对每组进行排序,只取每组中的第一个(最早的)。结果将是最早的任命:

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());
比如说,如果要用
早期记录的记录替换早期记录,只需执行以下操作:

patients = earliestAppointmentRecorded.ToList();
请尝试以下操作:

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

        }
static void Main(字符串[]args)
{
DataTable dt=新的DataTable();
添加(“名称”,类型(字符串));
添加(“约会类型”,类型(字符串));
添加(“约会日期”,类型(日期时间));
添加(新对象[]{“Ali”,“dental”,DateTime.Parse(“8/5/2017 08:00:00”)});
添加(新对象[]{“Ali”,“dental”,DateTime.Parse(“8/5/2017 16:00:00”);
var groups=dt.AsEnumerable().GroupBy(x=>new{name=x.Field(“name”),type=x.Field(“约会类型”))).ToList();
dt=groups.Select(x=>x.OrderBy(y=>y.Field(“约会日期”)).LastOrDefault()).CopyToDataTable();
}

首先在Where中过滤它们,然后按如下所述应用RemoveRange:
        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();

        }