LINQ表达式-动态From &Where子句

本文关键字:Where 子句 From 动态 表达式 LINQ | 更新日期: 2023-09-27 18:05:35

我有以下整数列表,我需要从count中提取包含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表达式-动态From &Where子句

与所有好的问题一样,解决这个问题的方法是使用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));

[已编辑]

可以将join和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的评论

我不确定它是否可以帮助你,但我如何实现基于条件的相同动态结果的想法。

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

我不确定演出内容。