我正在尝试使用linq解决以下问题(已经通过正常编程解决了它):
http://projecteuler.net/problem=43
我目前有以下内容:
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();
}
}
我最终希望扩展此查询以获取9个值,但目前,我的问题是,如果每个值都不同,我如何检查where子句? val0 val1和val3必须不同。
答案 0 :(得分:7)
怎么样
where new List<int> { val0, val1, val2 }.Distinct().Count() == 3
&& (val0 + val1 + val2 == 2)
答案 1 :(得分:1)
将值放入List中,获取不同的值并检查您拥有的项目数。
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() };
答案 2 :(得分:0)
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() };