根据条件防止数组重复
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());
Results.GroupBy(item => item.id).Select(x => x.First());
输入和预期输出的另一个示例:
回答
You can write your own extension method that works like the built-in LINQ methods:
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;
}
}
}
}
The usage is
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();