从集合中删除重复项,但第一次出现的项除外
本文关键字:第一次 集合 删除 | 更新日期: 2023-09-27 18:14:30
我有一个string类型的集合,它可以包含任意数量的元素。
现在我需要找出所有重复的元素,只找出第一次出现的重复元素,并删除其余的。
为例
public class CollectionCategoryTitle
{
public long CollectionTitleId { get; set; }
public bool CollectionTitleIdSpecified { get; set; }
public string SortOrder { get; set; }
public TitlePerformance performanceField { get; set; }
public string NewOrder { get; set; }
}
List<CollectionCategoryTitle> reorderTitles =
(List<CollectionCategoryTitle>)json_serializer
.Deserialize<List<CollectionCategoryTitle>>(rTitles);
现在我需要以这样一种方式处理这个集合:它删除重复项,但必须保留第一个出现项。
编辑:我已经更新了代码,我需要比较"NewOrder"属性
谢谢
具体情况:
var withoutDuplicates = reorderTitles.GroupBy(z => z.NewOrder).Select(z => z.First()).ToList();
对于更一般的情况,Distinct()通常更可取。例如:
List<int> a = new List<int>();
a.Add(4);
a.Add(1);
a.Add(2);
a.Add(2);
a.Add(4);
a = a.Distinct().ToList();
将返回4,1,2。注意,Distinct不能保证返回数据的顺序(当前的实现似乎是根据原始数据的顺序返回它们——但这是没有文档记录的,因此不应该依赖)。
使用Enumerable.Distinct<T>()
扩展方法来完成此操作。
EDIT: mjwills正确地指出,保证排序在问题中很重要,因此其他两个建议没有明确保证起作用。只留下一个提供这个保证的。
private static IEnumerable<CollectionCategoryTitle> DistinctNewOrder(IEnumerable<CollectionCategoryTitle> src)
{
HashSet<string> seen = new HashSet<string>();
//for one last time, change for different string comparisons, such as
//new HashSet<string>(StringComparer.CurrentCultureIgnoreCase)
foreach(var item in src)
if(seen.Add(item.NewOrder))
yield return item;
}
/*...*/
var distinctTitles = reorderTitles.DistinctNewOrder().ToList();
最后,只有在调用DistinctNewOrder()
之后才使用.ToList()
,如果您确实需要它是一个列表。如果您打算处理一次结果,然后不做进一步的工作,那么您最好不要创建一个浪费时间和内存的列表。