Linq that automatically eliminates duplicates (single line)

I have a linq request for project 243 eiler problem:

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

The problem is that for prime factors 2 and 3 it generates y = {6, 6}, where it should 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 that I cannot use indexing, so that would be just cumbersome and inconvenient.

+6
source share
2 answers

As pointed out by Rick Sladkey , change

  from m in factors where m != n 

to

  from m in factors where m < n 

gives the correct result without using .Distinct() .

+1
source

You can make a separate call for the resulting values. This way you do not need to do this in the inner loop.

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

If factors = new[] { 2,3 } you will 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 } . Please note if an additional 12 not obtained as a result.

+1
source

Source: https://habr.com/ru/post/899755/


All Articles