使用动态列输入LINQ构建自定义where子句

时间:2015-04-30 07:45:47

标签: c# linq lambda

在下面的lambda表达式中,我在where子句中有三列,根据我从数据库获得的输入可能有所不同,如果它是一个静态列表我可以构建如下表达式,但它是动态的我需要动态添加where子句,我在where子句中的列数将等于列表中的项数。所以我需要建立一个循环或什么,我将如何实现它。

dt.AsEnumerable().Where(x => (Convert.ToDecimal(x["Total"]) <= list[0] && Convert.ToDecimal(x["bal"]) <= list[1] && Convert.ToDecimal(x["issued"]) <= list[2])).ToList().Count;

2 个答案:

答案 0 :(得分:1)

我设法使linq动态

 var dynamicQuery = dt.AsEnumerable(); //to add dynamic where clause, first convert datatable to enumerable.
                    foreach(string name in columnName) //maintaining column names in a seperate list, as list would be dynamic
                    {
                        dynamicQuery = dynamicQuery.Where(r => (Convert.ToDecimal(r[name]) <= list[columnName.IndexOf(name)]));
                    }
                    int count=dynamicQuery.Count();

答案 1 :(得分:0)

我通常会创建一个词典

&#13;
&#13;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            //get a dictionary the contains a double as a key and the value
            // the count of the number of times the key occurs
            Dictionary<double, int> dict = dt.AsEnumerable()
                .GroupBy(x => x.Field<double>("Total"), y => y)
                .ToDictionary(x => x.Key, y => y.ToList().Count);
            //sample number of key to lookup
            double num = 778.660;
            //get the number of times the key appears in the input data.
            int count = dict[num];
        }
    }
}
​
&#13;
&#13;
&#13;