问题描述
C#/.NET应用程序编程开发中,使用LINQ对集合进行操作是一件非常令人愉悦的事件,因为LINQ内置了许多专门操作集合的方法,如:筛选(Where),查询(Select,SelectMany),求和(Sum)等等,这些方法可大大提高我们的开发效率,以便快速完成开发工作。
但很多时候需求是变化的,比如使用LINQ进行筛选(Where)条件的操作。一般情况下,我们使用Where
方法可能是这样的:
(from u in DataContext.Users
where u.Division == strUserDiv
&& u.Age > 18
&& u.Height > strHeightinFeet
select new
{
Prop1 = u.Name,
}).ToList();
这里的where条件是硬编码的,也就是说开发者事先知道Division
,Age
以及Height
这三个条件。如果在未知查询条件,即:需要动态添加LINQ的where条件,应该如何实现呢?
方案一
在C#/.NET中,如何使用LINQ进行查询,在还未调用.ToList()
方法之前,可以重复调用.Where()
方法进行查询条件的叠加,比如最开始的LINQ语句如下:
(from u in DataContext.Users
where u.Division == strUserDiv
select u;
我们可以重复调用.Where()
方法,来动态添加where查询条件,如下:
var query = (from u in DataContext.Users
where u.Division == strUserDiv
select u;
if (useAge)
query = query.Where(u => u.Age > age);
if (useHeight)
query = query.Where(u => u.Height > strHeightinFeet);
var results = query.Select(u => new
{
Prop1 = u.Name,
}).ToList();
方案二
使用IQueryable
创建一个泛型的静态扩展方法,如下:
public static IQueryable<T> ConditionalWhere<T>(
this IQueryable<T> source,
Func<bool> condition,
Expression<Func<T, bool>> predicate)
{
if (condition())
{
return source.Where(predicate);
}
return source;
}
调用示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace ConsoleApp2
{
class Program
{
public static void Main()
{
var list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 50, 60 };
var query = (from n in list where n > 5 select n).AsQueryable();
var age = 10;
query = query.ConditionalWhere(() => age > 0, x => x % 5 == 0);
var result = query.ToList();
Console.WriteLine(string.Join(",",result));
Console.ReadLine();
}
}
public static class QueryableExtensions
{
public static IQueryable<T> ConditionalWhere<T>(
this IQueryable<T> source,
Func<bool> condition,
Expression<Func<T, bool>> predicate)
{
if (condition())
{
return source.Where(predicate);
}
return source;
}
}
}
郑重申明:本文未经许可,禁止任何形式转载
发表评论
登录用户才能发表评论, 请 登 录 或者 注册