我有一个 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
在上面的示例中,最后一个字段是 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);
我现在该怎么办?现在我有了重复的 key 。 我想我需要再次检查 OriginalRecords 列表,看看它是否包含重复键。 然后在日期时间上使用子字符串。将其存储在某处,然后删除不是最新的记录。并用过滤器保存原始记录。谢谢
最佳答案
你不需要明确地找到重复的键,你可以简单地从每组中选择第一个:
var res == originalRecords
.GroupBy(x => x.RecordId)
.Select(g => g.OrderByDescending(x => x.DateTimeField).First());
There is no field for datetimefield as in your code. I simply have a string field which contains the datetime together with other data. The record however has a Record Id field.
您可以在破折号上拆分您的记录,获取日期时间部分,然后对其进行排序。您的日期/时间采用的格式可以让您按字典顺序排序,因此您可以跳过解析日期。
假设没有破折号,并且所有字符串的格式都相同,x.TextString.Split('-')[3]
表达式将为您提供字符串的时间戳部分记录:
var res == originalRecords
.GroupBy(x => x.RecordId)
.Select(g => g.OrderByDescending(x => x.TextString.Split('-')[3]).First());
关于C# 如何过滤列表并删除重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38902309/