Caleb Jares
Caleb Jares

Reputation: 6307

Linq query that automatically excludes duplicates (one-liner)

I have a linq query for project euler problem 243:

var y = from n in factors
        from m in factors where m != n
        select n * m;

The problem is, for prime factors 2 and 3, it produces the y = {6, 6} where it needs to just be {6}.

Is there a way to do this without calling y.Distinct() or y.Contains() multiple times?

I also thought about using two foreach loops, but the problem is - I can't use indexing so it'd just be cumbersome and awkward.

Upvotes: 6

Views: 471

Answers (2)

Caleb Jares
Caleb Jares

Reputation: 6307

As stated by Rick Sladkey, changing

    from m in factors where m != n

to

    from m in factors where m < n

produces the correct result without having to use .Distinct().

Upvotes: 1

Jason
Jason

Reputation: 3806

You can do a distinct call on the resulting values. This way you don't have to do it on the inner loop.

var y = factors.SelectMany(n => factors.Where(m => n < m).Select(m => n * m)).Distinct();

If factors = new[] { 2,3 } you get { 6 } as the result. Also if factors = new[] { 2,3,4,6 } you get { 6,8,12,18,24 } instead of { 6,8,12,12,18,24 }. Notice without the extra 12 in the result.

Upvotes: 1

Related Questions