From 55b2184c2c4e237a2dcbf4342f60bc92b43c86d3 Mon Sep 17 00:00:00 2001 From: witskeeper Date: Tue, 26 Nov 2024 13:43:04 +0800 Subject: [PATCH] add whereif --- .../IQueryableExtensions.cs | 30 +++++++++++++++++++ .../IQueryableExtensionsTests.cs | 17 +++++++++++ 2 files changed, 47 insertions(+) create mode 100644 src/NetCorePal.Extensions.Dto/IQueryableExtensions.cs create mode 100644 test/NetCorePal.Extensions.Dto.Tests/IQueryableExtensionsTests.cs diff --git a/src/NetCorePal.Extensions.Dto/IQueryableExtensions.cs b/src/NetCorePal.Extensions.Dto/IQueryableExtensions.cs new file mode 100644 index 00000000..66a7e78d --- /dev/null +++ b/src/NetCorePal.Extensions.Dto/IQueryableExtensions.cs @@ -0,0 +1,30 @@ +using System.Linq.Expressions; + +namespace NetCorePal.Extensions.Dto; + +/// +/// +/// +public static class IQueryableExtensions +{ + /// + /// 根据条件决定是否使用表达式进行where查询 + /// + /// 原始查询集合 + /// 如果为true,则使用where表达式,否则不使用表达式 + /// 用于where的条件表达式 + /// The type of the data in the data source + /// 如果condition为true,则返回使用了表达式predicate的where结果;否则,返回原source + public static IQueryable WhereIf( + this IQueryable source, + bool condition, + Expression> predicate) + { + if (condition) + { + return source.Where(predicate); + } + + return source; + } +} \ No newline at end of file diff --git a/test/NetCorePal.Extensions.Dto.Tests/IQueryableExtensionsTests.cs b/test/NetCorePal.Extensions.Dto.Tests/IQueryableExtensionsTests.cs new file mode 100644 index 00000000..4f60240c --- /dev/null +++ b/test/NetCorePal.Extensions.Dto.Tests/IQueryableExtensionsTests.cs @@ -0,0 +1,17 @@ +namespace NetCorePal.Extensions.Dto.Tests; + +public class IQueryableExtensionsTests +{ + [Fact] + public void WhereIfTests() + { + var data = new List { 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); + } +} \ No newline at end of file