Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where inside a where in linq

Tags:

c#

linq

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.

like image 610
NomenNescio Avatar asked Feb 22 '23 14:02

NomenNescio


2 Answers

How about

where new List<int> { val0, val1, val2 }.Distinct().Count() == 3
   && (val0 + val1 + val2 == 2)
like image 179
sq33G Avatar answered Feb 25 '23 04:02

sq33G


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() };
like image 43
Geoff Appleford Avatar answered Feb 25 '23 04:02

Geoff Appleford