Reputation: 3030
I'm I'm trying to solve the following problem with linq (already solved it with normal programming):
http://projecteuler.net/problem=43
I currently have the following:
class Program
{
static void Main(string[] args)
{
var range0 = Enumerable.Range(0, 3);
var range1 = Enumerable.Range(0, 3);
var range2 = Enumerable.Range(0, 3);
var combo = from val0 in range0
from val1 in range1
from val2 in range2
where (val0 + val1 + val2 == 3)
select new { value = val0.ToString() + val1.ToString() + val2.ToString() };
foreach( var value in combo )
{
Console.WriteLine(value.value);
}
Console.ReadLine();
}
}
I eventually want to extend this query to take 9 values, but currently, my question is, how do I check in the where clause if each value is distinct? val0 val1 and val3 have to be different.
Upvotes: 4
Views: 1550
Reputation: 18832
Put the values in a List, get the distinct values and check how many items you have.
var combo = from val0 in range0
from val1 in range1
from val2 in range2
let values = new List<int>() {val0, val1, val2}
where (val0 + val1 + val2 == 2) && values.Distinct().Count() == 3
select new { value = val0.ToString() + val1.ToString() + val2.ToString() };
Upvotes: 1
Reputation: 3360
How about
where new List<int> { val0, val1, val2 }.Distinct().Count() == 3
&& (val0 + val1 + val2 == 2)
Upvotes: 7
Reputation: 33637
from val0 in range0
from val1 in range1
where val1 != val0
from val2 in range2
where val2 != val1 && val2 != val0 && (val0 + val1 + val2 == 2)
select new { value = val0.ToString() + val1.ToString() + val2.ToString() };
Upvotes: 0