我有以下整数列表,我需要从 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();
最佳答案
与所有好问题一样,解决这个问题的方法是使用 Linq 和递归!
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));
关于c# - LINQ 表达式 - 动态来源和位置子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23906306/