Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 248
Caleb Jares Avatar asked Oct 21 '11 03:10

Caleb Jares


2 Answers

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.

like image 86
Jason Avatar answered Oct 13 '22 17:10

Jason


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

like image 35
Caleb Jares Avatar answered Oct 13 '22 19:10

Caleb Jares