list根据某个字段去重之后依旧返回该list

博客主要提及对list根据某个属性字段进行去重的内容,聚焦于信息技术中数据处理方面的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Map<Object, Boolean> map = new HashMap<>();
            dtoList = dtoList.stream().filter(i -> map.putIfAbsent(i.getCompanyName(), Boolean.TRUE) == null).collect(Collectors.toList());

list根据某个属性字段做去重

List<Entity> distinctList = list.stream()
                                .distinct()
                                .collect(Collectors.collectingAndThen(
                                    Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Entity::getProperty))),
                                    ArrayList::new));

### 如何在 C# 中根据特定字段List 进行 在 C# 中,可以通过多种方式实现基于特定字段操作。以下是一个使用 LINQ 的方法来完成此任务的示例: #### 使用 `GroupBy` 方法 可以利用 LINQ 的 `GroupBy` 方法,按指定字段分组,并取每组的第一个元素以实现。 ```csharp using System; using System.Collections.Generic; using System.Linq; public class Item { public int Id { get; set; } public string Name { get; set; } } public class Program { public static void Main() { List<Item> items = new List<Item> { new Item { Id = 1, Name = "Apple" }, new Item { Id = 2, Name = "Banana" }, new Item { Id = 1, Name = "Orange" }, new Item { Id = 3, Name = "Grape" }, new Item { Id = 2, Name = "Pineapple" } }; // 按 Id 字段 var distinctItems = items .GroupBy(i => i.Id) .Select(g => g.First()) .ToList(); foreach (var item in distinctItems) { Console.WriteLine($"Id: {item.Id}, Name: {item.Name}"); } } } ``` 上述代码中,`GroupBy` 方法将列表中的对象按 `Id` 字段分组[^5],然后通过 `Select` 方法从每个分组中选择第一个元素,从而实现效果。 #### 使用自定义比较器 另一种方法是创建一个自定义的 `IEqualityComparer<T>` 实现,并将其传递给 `Distinct` 方法。 ```csharp using System; using System.Collections.Generic; using System.Linq; public class Item { public int Id { get; set; } public string Name { get; set; } } public class ItemComparer : IEqualityComparer<Item> { public bool Equals(Item x, Item y) { return x.Id == y.Id; } public int GetHashCode(Item obj) { return obj.Id.GetHashCode(); } } public class Program { public static void Main() { List<Item> items = new List<Item> { new Item { Id = 1, Name = "Apple" }, new Item { Id = 2, Name = "Banana" }, new Item { Id = 1, Name = "Orange" }, new Item { Id = 3, Name = "Grape" }, new Item { Id = 2, Name = "Pineapple" } }; // 使用自定义比较器 var distinctItems = items.Distinct(new ItemComparer()).ToList(); foreach (var item in distinctItems) { Console.WriteLine($"Id: {item.Id}, Name: {item.Name}"); } } } ``` 在此代码中,`ItemComparer` 类实现了 `IEqualityComparer<Item>` 接口,定义了如何比较两个 `Item` 对象[^6]。通过将该比较器传递给 `Distinct` 方法,可以基于 `Id` 字段进行。 ### 注意事项 - 如果需要基于多个字段进行,可以在 `Equals` 和 `GetHashCode` 方法中添加额外的逻辑。 - 使用 `GroupBy` 方法时,可以选择保留每组的第一个元素或其他逻辑(如最后一个元素或某个条件下的元素)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值