C # Trying to avoid duplicates

var multiples = from i in Enumerable.Range(min, (max - min)) from r in roots where i % r == 0 select i; 

For example, if roots = {2,10} , he chooses 20 twice.

Can duplication be avoided here?

+6
source share
4 answers

You can use Any() instead of a full Cartesian union:

 var multiples = from i in Enumerable.Range(min, (max - min)) where roots.Any(r => i % r == 0) select i; 

This has the added benefit of stopping testing elements in roots as soon as he finds one that succeeds, and he doesn't need a second pass to pull out individual elements.

+8
source

Use distinct

 var multiples = (from i in Enumerable.Range(min, (max - min)) from r in roots where i % r == 0 select i).Distinct(); 

This works well on simple types like string and int . not very good on anonymous types.

In your case, i is an int , and so it must be aware of dublicates.

EDIT

It works with anonymous types (see Jeppe comment). because, as @Jeppe said, anonymous types have a “good” Equals enabeling Distict to determine if objects are equal / duplicated.

+11
source

Use DISTINCT

 var multiples = (from i in Enumerable.Range(min, (max - min)) from r in roots where i % r == 0 select i).Distinct(); 
+4
source

Use the Distinct() Method

 var multiples = (from i in Enumerable.Range(min, (max - min)) from r in roots where i % r == 0 select i).Distinct(); 
+1
source

All Articles