Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
112 views
in Technique[技术] by (71.8m points)

c# - Prevent duplicates from array, based on condition


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();

Online demo: https://dotnetfiddle.net/QDpCDF

EDIT: If you want to use a property of the objects in your list (like an ID property), you can add some slight modifications to the method:

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;
            }
        }
    }
}

The usage is

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...