构建动态LINQ?

时间:2010-03-22 15:22:28

标签: linq

我正在使用LINQ来查询数据。考虑一个用户只想报告3个字段中的1个字段的情况? (见下文)

有谁能告诉我如何动态构建查询?

由于

DD

var query =
    from cl in db.tblClaims
    join cs in db.tblCases
        on cl.ref_no equals cs.ref_no
    where cl.claim_status == "Appeal"
        && cl.appeal_date >= Convert.ToDateTime(txtReferedFromDate.Text)
        && cl.appeal_date <= Convert.ToDateTime(txtReferedToDate.Text)
        && cs.referred_from_lho == dlLHO.Text
        && cs.adviser == dlAdviser.Text
    select new
    {
        Ref = cs.ref_no,
        ClaimType = cl.claim_type,
        ClaimStatus = cl.claim_status,
        AppealDate = cl.appeal_date
    };

gvReport.DataSource = query;

4 个答案:

答案 0 :(得分:5)

我们通过传入Criteria对象然后通过使用表达式树附加所需条件来构建查询。

IQueryable<Data.Story> query = ctx.DataContext.Stories;

if (criteria.StoryId != null) // StoryId
    query = query.Where(row => row.StoryId == criteria.StoryId);

if (criteria.CustomerId != null) // CustomerId
    query = query.Where(row => row.Project.CustomerId == criteria.CustomerId);

if (criteria.SortBy != null) // SortBy
    query = query.OrderBy(criteria.SortBy + " " + criteria.SortOrder.Value.ToStringForSql());

if (criteria.MaximumRecords != null) // MaximumRecords
    query = query.Take(criteria.MaximumRecords.Value);

var data = query.Select(row => StoryInfo.FetchStoryInfo(row));

您还可以在http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

查看Dynamic Linq库

答案 1 :(得分:5)

你可以这样做:

var query = from cl in db.tblClaims
                        join cs in db.tblCases
                            on cl.ref_no equals cs.ref_no
                        where cl.claim_status == "Appeal"
                        select new
                        {
                            Ref = cs.ref_no,
                            ClaimType = cl.claim_type,
                            ClaimStatus = cl.claim_status,
                            AppealDate = cl.appeal_date,
                            cs.referred_from_lho,
                            cs.adviser
                        };

if(!string.IsNullOrEmpty(txtReferedFromDate.Text) 
   && !string.IsNullOrEmpty(txtReferedToDate.Text))
  query = query.Where(cl => 
                   cl.appeal_date >= Convert.ToDateTime(txtReferedFromDate.Text) 
                && cl.appeal_date <= Convert.ToDateTime(txtReferedToDate.Text));

if(!string.IsNullOrEmpty(dlLHO.Text))
  query = query.Where(cl => cl.referred_from_lho == dlLHO.Text);

if(!string.IsNullOrEmpty(dlAdviser.Text))
  query = query.Where(cl => cl.adviser == dlAdviser.Text);

gvReport.DataSource = 
      query.Select(o => new { o.Ref, o.ClaimType, o.ClaimStatus, o.AppealDate });

如果它们具有要过滤的值,则只会将这些字段用作过滤器,否则它们将不会在查询中使用。

答案 2 :(得分:1)

Microsoft已经创建了一个示例库(Linq Dynamic Library),允许您在Linq中构建动态查询,您可以看到如何使用它并从此链接下载它: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

话虽如此,您也可以在代码开头声明IQueriable,并根据参数添加where子句。我打算写一个例子,但是mattruma打败了我:)

我更喜欢第二种选择,但有些情况下使用动态库是一种更好的解决方案。

答案 3 :(得分:0)

像这样:

namespace overflow4
{
    class Program
    {
        static void Main(string[] args)
        {
            var orig = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };

            var newlist = FilterNumbers(orig, true, false, false);

            foreach (int x in newlist)
                Console.WriteLine(x);
            Console.ReadLine();
        }

        private static IEnumerable<int> FilterNumbers(
            List<int> origlist, 
            bool wantMultiplesOf2, 
            bool wantMultiplesOf3, 
            bool wantMultiplesOf5)
        {
            IEnumerable<int> sofar = origlist;

            if (wantMultiplesOf2)
                sofar = sofar.Where(n => n % 2 == 0);

            if (wantMultiplesOf3)
                sofar = sofar.Where(n => n % 3 == 0);

            if (wantMultiplesOf5)
                sofar = sofar.Where(n => n % 5 == 0);

            return sofar;
        }
    }
}