-
Notifications
You must be signed in to change notification settings - Fork 43
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #117 from netcorepal/whereif
add whereif
- Loading branch information
Showing
2 changed files
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
using System.Linq.Expressions; | ||
|
||
namespace NetCorePal.Extensions.Dto; | ||
|
||
/// <summary> | ||
/// | ||
/// </summary> | ||
public static class IQueryableExtensions | ||
{ | ||
/// <summary> | ||
/// 根据条件决定是否使用表达式进行where查询 | ||
/// </summary> | ||
/// <param name="source">原始查询集合</param> | ||
/// <param name="condition">如果为true,则使用where表达式,否则不使用表达式</param> | ||
/// <param name="predicate">用于where的条件表达式</param> | ||
/// <typeparam name="T">The type of the data in the data source</typeparam> | ||
/// <returns>如果condition为true,则返回使用了表达式predicate的where结果;否则,返回原source</returns> | ||
public static IQueryable<T> WhereIf<T>( | ||
this IQueryable<T> source, | ||
bool condition, | ||
Expression<Func<T, bool>> predicate) | ||
{ | ||
if (condition) | ||
{ | ||
return source.Where(predicate); | ||
} | ||
|
||
return source; | ||
} | ||
} |
17 changes: 17 additions & 0 deletions
17
test/NetCorePal.Extensions.Dto.Tests/IQueryableExtensionsTests.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
namespace NetCorePal.Extensions.Dto.Tests; | ||
|
||
public class IQueryableExtensionsTests | ||
{ | ||
[Fact] | ||
public void WhereIfTests() | ||
{ | ||
var data = new List<int> { 1, 2, 3, 4, 5 }.AsQueryable(); | ||
var result = data.WhereIf(true, x => x > 3).ToList(); | ||
Assert.Equal(2, result.Count); | ||
Assert.Equal(4, result[0]); | ||
Assert.Equal(5, result[1]); | ||
|
||
result = data.WhereIf(false, x => x > 3).ToList(); | ||
Assert.Equal(5, result.Count); | ||
} | ||
} |