C#如何过滤列表并删除重复项?

use*_*420 2 .net c# linq

我有一个类型X的列表.这包含字段,我需要从列表中只返回唯一的记录.我需要使用包含时间戳的字段/属性(OIndex)之一并使用该属性对其进行过滤.列表是这样的:

> 2c55-Checked-branchDeb-20160501121315-05
> 2c60-Checked-branchDeb-20160506121315-06
> 2c55-Checked-branchDeb-20160601121315-07
> 2c55-Checked-branchDeb-20160601141315-07
> 2c60-Checked-branchDeb-20160720121315-08
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,最后一个字段是recordId,因此我们有一个重复的记录"07".时间戳是第四场.所以我想获得所有记录,除了第3个是重复的.记录"07"的最新版本是第四行.

我开始做代码但很挣扎.至今:

List<X> originalRecords = GetSomeMethod(); //this method returns our list above

var duplicateKeys = originalRecords.GroupBy(x => x.Record)  //x.Record is the record as shown above "05", "06" etc
                        .Where(g => g.Count() > 1)
                        .Select(y => y.Key);
Run Code Online (Sandbox Code Playgroud)

现在我该怎么做?现在我有了重复的密钥.我想我需要再次查看OriginalRecords列表,看看它是否包含重复键.然后在datetime上使用substring.将其存储在某处,然后删除不是最新的记录.并使用过滤器保存原始记录.谢谢

das*_*ght 7

您不需要明确地找到重复的键,您只需从每个组中选择第一个:

var res == originalRecords
    .GroupBy(x => x.RecordId)
    .Select(g => g.OrderByDescending(x => x.DateTimeField).First());
Run Code Online (Sandbox Code Playgroud)

在代码中没有datetimefield的字段.我只是有一个字符串字段,其中包含日期时间和其他数据.但是该记录有一个Record Id字段.

您可以在短划线上拆分记录,获取日期时间部分,然后对其进行排序.您的日期/时间采用允许按字典顺序排序的格式,因此您可以跳过解析日期.

假设没有破折号,并且所有字符串都以相同的方式格式化,x.TextString.Split('-')[3]表达式将为您提供记录的时间戳部分:

var res == originalRecords
    .GroupBy(x => x.RecordId)
    .Select(g => g.OrderByDescending(x => x.TextString.Split('-')[3]).First());
Run Code Online (Sandbox Code Playgroud)