我有以下整数列表,我需要提取不同的整数列表,其中包含2-4个数字的数字。下面的代码将提取仅包含2个数字的列表。
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();
有没有办法动态地建立这个Linq表达式,这样如果我想要3个数字的列表,它将被编译如下,这将节省我必须在不同的方法中打包相似的表达式。
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();
答案 0 :(得分:1)
与所有好问题一样,解决这个问题的方法是Linq和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));
答案 1 :(得分:0)
<强> [编辑] 强>
您可以将连接和where子句与循环和条件组合在一起,例如:
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; });
(返回List而不是匿名对象)
编辑2:感谢Aron的评论。
答案 2 :(得分:0)
我不确定它是否可以帮助你,但我知道如何根据条件获得相同的动态结果。
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
我不确定表演会是什么。