chillydk147
chillydk147

Reputation: 385

LINQ Expression - Dynamic From & Where Clause

I have the following list of integers that I need to extract varying lists of integers containing numbers from say 2-4 numbers in count. The code below will extract lists with only 2 numbers.

var numList = new List<int> { 5, 20, 1, 7, 19, 3, 15, 60, 3, 21, 57, 9 };

var selectedNums = (from n1 in numList
                    from n2 in numList
                    where (n1 > 10) && (n2 > 10)
                    select new { n1, n2 }).ToList(); 

Is there any way to build up this Linq expression dynamically so that if I wanted lists of 3 numbers it would be compiled as below, this would save me having to package the similar expression inside a different method.

var selectedNums = (from n1 in numList
                    from n2 in numList
                    from n3 in numList
                    where (n1 > 10) && (n2 > 10) && (n3 > 10)
                    select new { n1, n2, n3 }).ToList();

Upvotes: 2

Views: 197

Answers (3)

Aron
Aron

Reputation: 15772

As with all good questions the way to solve this is with Linq and with Recursion!

    public IEnumerable<IEnumerable<T>> Permutation<T>(int count, IEnumerable<T> sequence)
    {
        if(count == 1)
        {
            foreach(var i in sequence)
            {
                yield return new [] { i };
            }
            yield break;
        }


        foreach(var inner in Permutation(count - 1, sequence))
        foreach(var i in sequence)
        {
            yield return inner.Concat(new [] { i });
        }        
    }

var foo = Permutation<int>(3, numList.Where(x => x > 10));

Upvotes: 1

Iti Tyagi
Iti Tyagi

Reputation: 3661

I am not sure if it can help you but an idea how I achieved the same dynamic result based on condition.

var q=(from n in context.TableName
       .......);

if(x!=null) //this can be the condition (you can have yours)
var final=q.Select(i=>i....); //I am using q again here

I am not sure what will be the performance.

Upvotes: 0

Joanvo
Joanvo

Reputation: 5817

[Edited]

You can combine joins and where clauses with loops and conditions, like that:

var q = numList.Where(x => x > 10).Select(x => new List<int>{ x });

for(i = 1; i <= numToTake; ++i)
  q = q.Join(numList.Where(x => x > 10), x=> 0, y => 0, (x, y) => { x.Add(y); return x; });

(that returns a List instead of an anonymous object)

Edit 2: Thanks Aron for the comment.

Upvotes: 0

Related Questions