Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq query that reduces a subset of duplicates to a single value within a larger set?

Tags:

c#

linq

Is there a linq command that will filter out duplicates that appear in a sequence?

Example with '4':

Original { 1 2 3 4 4 4 5 6 7 4 4 4 8 9 4 4 4 }
Filtered { 1 2 3 4 5 6 7 4 8 9 4 }

Thanks.

like image 872
E.Beach Avatar asked Nov 05 '10 23:11

E.Beach


People also ask

What is any () in LINQ?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.

What is the advantage of LINQ in C#?

Advantages of Using LINQLINQ offers a common syntax for querying any type of data sources. Secondly, it binds the gap between relational and object-oriented approachs. LINQ expedites development time by catching errors at compile time and includes IntelliSense & Debugging support. LINQ expressions are Strongly Typed.


1 Answers

Not really. I'd write this:

public static IEnumerable<T> RemoveDuplicates(this IEnumerable<T> sequence)
{
    bool init = false;
    T current = default(T);

    foreach (var x in sequence)
    {
        if (!init || !object.Equals(current, x))
            yield return x;

        current = x;
        init = true;
    }   
}
like image 199
mqp Avatar answered Nov 04 '22 01:11

mqp