LINQ Expression - Dynamic From & Where Clause
Posted
by
chillydk147
on Stack Overflow
See other posts from Stack Overflow
or by chillydk147
Published on 2014-05-28T08:22:47Z
Indexed on
2014/05/29
9:27 UTC
Read the original article
Hit count: 160
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();
© Stack Overflow or respective owner