Skip to content

Commit

Permalink
Merge pull request #117 from netcorepal/whereif
Browse files Browse the repository at this point in the history
add whereif
  • Loading branch information
witskeeper authored Nov 26, 2024
2 parents 1cb5a49 + 55b2184 commit 4961467
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/NetCorePal.Extensions.Dto/IQueryableExtensions.cs
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 test/NetCorePal.Extensions.Dto.Tests/IQueryableExtensionsTests.cs
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);
}
}

0 comments on commit 4961467

Please sign in to comment.