首页 > 解决方案 > 根据条件防止数组重复

问题描述

我有一组数字,我需要防止重复。对于数组中大于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"]}

标签: c#.netlinqdelegates

解决方案


您可以编写自己的扩展方法,其工作方式类似于内置 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();

推荐阅读