c# - 根据条件防止数组重复
问题描述
我有一组数字,我需要防止重复。对于数组中大于0
. 例如,如果输入为 [0,0,0,1,1,1,1,1,2,2],则输出应为:[0,0,0,1,2]。有人能帮我吗?我已经尝试了下面的代码,但我得到了这样的结果 [0,1,2]。
Results.GroupBy(item => item.id).Select(x => x.First());
输入和预期输出的另一个示例:
Input: {[id=0,Name="test0"],[id=0,Name="test0"], [id=1,Name="test1"],[id=1,Name="test1"],[id=1,Name="test1"],[id=2,Name="test2"],[id=2,Name="test2"]}
Output: {[id=0,Name="test0"],[id=0,Name="test0"],[id=1,Name="test1"],[id=2,Name="test2"]}
解决方案
您可以编写自己的扩展方法,其工作方式类似于内置 LINQ 方法:
public static class Extensions
{
public static IEnumerable<T> DistinctWhere<T>(this IEnumerable<T> input, Func<T,bool> predicate)
{
HashSet<T> hashset = new HashSet<T>();
foreach(T item in input)
{
if(!predicate(item))
{
yield return item;
continue;
}
if(!hashset.Contains(item))
{
hashset.Add(item);
yield return item;
}
}
}
}
用法是
int[] input = new int[] { 0,0,0,1,1,1,1,1,2,2 };
int[] result = input.DistinctWhere(x => x > 0).ToArray();
在线演示:https ://dotnetfiddle.net/QDpCDF
编辑:如果您想使用列表中对象的属性(如 ID 属性),您可以对该方法添加一些细微的修改:
public static class Extensions
{
public static IEnumerable<T> DistinctWhere<T,T2>(this IEnumerable<T> input, Func<T,T2> selector, Func<T2,bool> predicate)
{
HashSet<T2> hashset = new HashSet<T2>();
foreach(T item in input)
{
T2 value = selector.Invoke(item);
if(!predicate.Invoke(value))
{
yield return item;
continue;
}
if(!hashset.Contains(value))
{
hashset.Add(value);
yield return item;
}
}
}
}
用法是
TypeWithId[] input = new TypeWithId[]
{
new TypeWithId { ID = 0 } ,
new TypeWithId { ID = 0 } , //... also initialize the other items
};
TypeWithId[] result = input.DistinctWhere(x => x.ID, x => x > 0).ToArray();
推荐阅读
- android - 如果我的应用程序在我的 Android Studio 模拟器上运行缓慢,我的应用程序在设备上是否会运行缓慢?
- java - 在尤里卡服务器中添加尤里卡客户端时出错,客户端模块无法启动
- mysql - mysql concat csv 从两列转换成密钥对
- ios - Apple 如何在 iOS 12 的 iBooks 应用中为一本书创建阴影效果?
- sql - 我可以在这个维度模型中改进什么?
- mysql - Calculate billing usage for current month
- tensorflow - CUDA 如何影响深度学习性能?
- ethereum - 有没有办法将以太坊令牌列入黑名单
- api - 如果我更改我的 Twitter 用户名,API 密钥会更改吗?
- javascript - 遵循 Leaflet JS 教程的“this.update 不是函数”