zijian666.AnyExtensions
1.0.1
.NET Standard 2.0
This package targets .NET Standard 2.0. The package is compatible with this framework or higher.
.NET Framework 4.5
This package targets .NET Framework 4.5. The package is compatible with this framework or higher.
There is a newer version of this package available.
See the version list below for details.
See the version list below for details.
dotnet add package zijian666.AnyExtensions --version 1.0.1
NuGet\Install-Package zijian666.AnyExtensions -Version 1.0.1
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="zijian666.AnyExtensions" Version="1.0.1" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add zijian666.AnyExtensions --version 1.0.1
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: zijian666.AnyExtensions, 1.0.1"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install zijian666.AnyExtensions as a Cake Addin #addin nuget:?package=zijian666.AnyExtensions&version=1.0.1 // Install zijian666.AnyExtensions as a Cake Tool #tool nuget:?package=zijian666.AnyExtensions&version=1.0.1
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
any-extensions
万物皆可扩展
时间扩展
DateTimeExtensions
1. 将时间类型转为日期时间字符串 yyyy-MM-dd HH:mm:ss
string ToDateTimeString(this DateTime datetime) { ... }
// 例:
var str = DateTime.Now.ToDateTimeString(); // 2022-08-12 22:26:03;
2. 将时间类型转为日期字符串 yyyy-MM-dd
string ToDateString(this DateTime datetime) { ... }
// 例:
var str = DateTime.Now.ToDateString(); // 2022-08-12;
3. 将时间类型转为时间字符串 HH:mm:ss
string ToTimeString(this DateTime datetime) { ... }
// 例:
var str = DateTime.Now.ToTimeString(); // 22:25:38;
4. 获取此实例时间所在的那一天的最后一秒
DateTime LastSecondsOfDay(this DateTime datetime) { ... }
// 例:
var time = DateTime.Now.LastSecondsOfDay(); // new DateTime("2022-08-12 23:59:59");
5. 获取此实例时间所在的那个月的第一天
DateTime FirstDayOfMonth(this DateTime datetime) { ... }
// 例:
var time = DateTime.Now.FirstDayOfMonth(); // new DateTime("2022-08-01 22:28:38");
6. 获取此实例时间所在的那个月的最后一天
DateTime LastDayOfMonth(this DateTime datetime) { ... }
// 例:
var time = DateTime.Now.LastDayOfMonth(); // new DateTime("2022-08-31 22:28:38");
7. 获取此实例时间所在的那一年的第一天
DateTime FirstDayOfYear(this DateTime datetime) { ... }
// 例:
var time = DateTime.Now.FirstDayOfYear(); // new DateTime("2022-01-01 22:29:53");
8. 获取此实例时间所在的那一年的最后一天
DateTime LastDayOfYear(this DateTime datetime) { ... }
// 例:
var time = DateTime.Now.LastDayOfYear(); // new DateTime("2022-12-31 22:29:53");
9. 获取此实例时间所在的那一周的星期日
// 参数: `firstDayOfWeek` 用于指示规则每周第一天是周几
DateTime SundayOfWeek(this DateTime datetime, DayOfWeek firstDayOfWeek = DayOfWeek.Monday) { ... }
// PS: MondayOfWeek,TuesdayOfWeek,WednesdayOfWeek,ThursdayOfWeek,FridayOfWeek,SaturdayOfWeek 功能类似
// 例:
var time = DateTime.Now.SundayOfWeek(); // new DateTime("2022-08-14 22:29:53");
ExceptionExtensions
异常操作扩展
1. 参数校验
// 开启参数校验
ParameterChecker<T> Check<T>(this T value, string paramName) { ... }
// 判断参数是否为null
ParameterChecker<T> ThrowIfNull<T>(this ParameterChecker<T> checker, string message = null) { ... }
// 判断参数是否为默认值
ParameterChecker<T> ThrowIfDefault<T>(this ParameterChecker<T> checker, string message = null) { ... }
// 判断参数(集合或字符串)是否为空
ParameterChecker<T> ThrowIfEmpty<T>(this ParameterChecker<T> checker, string message = null) { ... }
// 例:
name.Check("name").ThrowIfNull().ThrowIfEmpty();
id.Check("id").ThrowIfNull().ThrowIfDefault();
entity.Check("entity").ThrowIfNull().ValidatEntity(); // ValidatEntity 由 zijian666.AnyExtensions.ComponentModel 提供;
2. 循环当前异常的所有内部异常
IEnumerable<Exception> GetAllExceptions(this Exception exception) { ... }
// 循环当前异常的所有指定类型的内部异常
IEnumerable<Exception> GetAllExceptions<T>(this Exception exception) where T : Exception { ... }
// 例:
ex.GetAllExceptions<BizException>().ToList();
3. 抛出第一个异常,如果没有则不执行任何操作
void ThrowFirstError<T>(this IEnumerable<T> exceptions) { ... }
// 例:
ex.GetAllExceptions<BizException>().ThrowFirstError();
4. 如果存在一个以上的异常,则尝试聚合异常后抛出; 如果只有一个异常直接抛出
void ThrowAllError<T>(this IEnumerable<T> exceptions) { ... }
// 例:
ex.GetAllExceptions<BizException>().ThrowAllError();
5. 如果异常不为空,则抛出异常
void Throw<T>(this T exception) { ... }
// 例:
ex.GetAllExceptions<BizException>().FirstOrDefault().Throw();
6. 如果有必要,聚合异常,默认最大聚合异常10个,超过则丢弃
Exception Aggregate<T>(this IEnumerable<T> exceptions, int max = 10) { ... }
// 例:
ex.GetAllExceptions<BizException>().Aggregate().Throw();
数字扩展
NumberExtensions
1. 将小数值舍入到指定精度,默认四舍五入
T Round(this T value, byte decimals, MidpointRounding mode = MidpointRounding.AwayFromZero) { ... }
// 例:
(2.345).Round(2); // 2.35;
2. 将小数值舍入到指定精度的整数,默认四舍五入
T Round(this T value, MidpointRounding mode = MidpointRounding.AwayFromZero) { ... }
// 例:
(0.5).Round(); // 1;
3. 返回大于或等于指定小数位的数
T Ceiling(this T value, byte decimals) { ... }
// 例:
(1.100005).Ceiling(1); // 1.2;
4. 返回小于或等于指定小数位的数
T Floor(this T value, byte decimals) { ... }
// 例:
(1.19).Floor(1); // 1.1;
5. 按指定模式和位数对数字进行处理
T Scale(this T value, NumberScaleMode mode) { ... }
T Scale(this T value, byte decimals, NumberScaleMode mode) { ... }
// 例:
(1.19).Scale(1, NumberScaleMode.Floor); // 1.1;
(0.55).Scale(1, NumberScaleMode.Round); // 0.6;
(1.101).Scale(1, NumberScaleMode.Ceiling); // 1.2;
## 布尔型扩展
> BooleanExtensions
```C#
// 取反
bool Not(this bool b) { ... }
// 有值 且为 true
bool IsTrue(this bool? b) { ... }
// 有值 且为 false
bool IsFalse(this bool? b) { ... }
// 值为 null 或 true
bool IsNullOrTrue(this bool? b) { ... }
// 值为 null 或 false
bool IsNullOrFalse(this bool? b) { ... }
// 例:
var b = users.Where(x=>x.id==1).Select(x=>x.deleted).FirstOrDefault();
if (b.IsNullOrTrue()) {
throw new Exception("用户不存在或已被删除");
}
字符串扩展
StringExtensions
1. 指示字符串是 null 还是空字符串 ("")。
bool IsNullOrEmpty(this string value) { ... }
// 例:
if("xxx".IsNullOrEmpty());
2. 指示字符串是 null、空还是仅由空白字符组成。
bool IsNullOrWhiteSpace(this string value) { ... }
// 例:
if("xxx".IsNullOrWhiteSpace());
3. 如果字符串是 null 或空字符串 (""),则返回 defaultValue
,否则根据 trim
确定是否需要前后去空格
string EmptyOrDefault(this string value, string defaultValue, bool trim = true) { ... }
// 例:
str = str.EmptyOrDefault("", true);
4. 如果字符串是null、空或是仅由空白字符组成,则返回 defaultValue
,否则根据 trim
确定是否需要前后去空格
string WhiteSpaceOrDefault(this string value, string defaultValue, bool trim = true) { ... }
// 例:
str = str.WhiteSpaceOrDefault("", true);
5. 按照指定符号切分字符串,并转为指定格式,如果不传默认分割为 `',', ' ', ';', '\n', '\r', '\t';
IEnumerable<T> Split<T>(this string value, params char[] separator) { ... }
// 例:
var ids = "1,2,3,4,5".Split<int>();
6. 包装 like 查询时可用的字符串
string EncodeSqlLike(this string value) { ... }
// 例:
Query($"select * from table where column like '%{str.EncodeSqlLike()}%'");
7. 包装 文件名 可用的字符串(主要是将半角改为全角)
string EncodeFileName(this string value) { ... }
// 例:
"1:2.txt".LikeWapper()` // 1:2.txt
## 枚举扩展
> EnumExtensions
### 1. 获取枚举值的描述
```C#
string GetDescription(this Enum value, bool nullToName = false) { ... }
// 例:
var str = BusinessStatuz.XXXX.GetDescription() ;
2. 拆分 FlagsAttribute
标记的枚举
IEnumerable<T> FlagsSplit<T>(this T @enum) where T : Enum { ... }
// 例:
var flags = (BindingFlags.Instance | BindingFlags.Public).FlagsSplit();
3. 合并枚举
T FlagsCombine<T>(this IEnumerable<T> enums) where T : Enum { ... }
// 例:
var flags = new[] { BindingFlags.Instance, BindingFlags.Public }.FlagsCombine();
4. 获取枚举对应的字段FieldInfo
FieldInfo GetFieldInfo<T>(this T key) where T : struct, Enum { ... }
// 例:
var field = BindingFlags.IgnoreCase.GetFieldInfo();
结构体扩展
StructExtensions
1. 判断值为空或默认值
bool IsNullOrDefault<T>(this T? value) where T : struct { ... }
// 例:
if(x.IsNullOrDefault()) { ... } ` 用于代替 ` x == null || x == default(T);
1. 判断值不是空或默认值
bool NotNullOrDefault<T>(this T? value) where T : struct { ... }
// 例:
if(x.NotNullOrDefault()) { ... } ` 用于代替 ` x != null && x != default(T);
CollectionExtensions
集合扩展
1. 返回排除空对象(null)后的去重集合
ICollection DistinctWithoutNull(this IEnumerable source) { ... }
// 例:
var ids = list.DistinctWithoutNull();
2. 获取字典中的值如果key不存在则返回默认值
TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue defaultValue = default) { ... }
// 例:
var val = dict.GetValueOrDefault(key, null);
3. 判断一个集合是否为空
bool IsNullOrEmpty(this IEnumerable value) { ... }
// 例:
if( list.IsNullOrEmpty() ) { ... };
4. 调用 string.Join 生成新的字符串
string Join(this IEnumerable source, string separator = ",") { ... }
// 例:
db.Where(...).Select(x => x.Code).Join(",");
5. 创建 HashSet
;
HashSet<T> ToHashSet<T>(this IEnumerable<T> source, IEqualityComparer<T> comparer = null) { ... }
// 例:
db.Where(...).Select(x => x.PId).HashSet();
6. 排除集合中的空对象(null)
IEnumerable<T> WithoutNull<T>(this IEnumerable<T> source) { ... }
// 例:
var list = ids.WithoutNull().ToList();
7. 转为只读集合
IReadOnlyCollection<T> AsReadOnly<T>(this IEnumerable<T> source) { ... }
IReadOnlyDictionary<TKey, TValue> AsReadOnly<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source) { ... }
// 例:
var list = array.AsReadOnly();
var dict = dict1.AsReadOnly();
8. 循环集合
IEnumerable<T> Each<T>(this IEnumerable<T> source, Action<T> action) { ... }
IEnumerable<T> Each<T>(this IEnumerable<T> source, Action<int, T> action) { ... }
// 例:
list.Each(x => Console.Write(x));
QueryableExtensions
待查询对象扩展
1. 确定序列中没有任何元素满足条件。参考集合扩展
bool IsNullOrEmpty<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate) { ... }
2. 创建 HashSet
。参考集合扩展
HashSet<TSource> ToHashSet<TSource>(this IQueryable<TSource> source, IEqualityComparer<TSource> comparer = null) { ... }
3. 构建 where {columnName} in ( {values} )
语句查询数据库
IQueryable<TSource> FindByIn<TSource, TKey>(this IQueryable<TSource> queryable, string columnName, IEnumerable<TKey> values) { ... }
IQueryable<TSource> FindByIn<TSource, TKey>(this IQueryable<TSource> queryable, Expression<Func<TSource, TKey>> selector, IEnumerable<TKey> values) { ... }
// 例:
db.FindByIn("Code", new []{"111","222","333"});
db.FindByIn(x => x.Code, new []{"111","222","333"});
4. 构建 where Id in ( {values} )
语句查询数据库
public static IQueryable<TSource> FindByIds<TSource, TId>(this IQueryable<TSource> queryable, IEnumerable<TId> ids) { ... }
// 例:
db.FindByIds(new []{1,2,3,4,5});
5. 排除已删除的数据,构建 where {IsDelete} != 1
语句查询数据库
// 参数 columnName 自定义标识删除的列名称
IQueryable<TSource> WithoutDeleted<TSource>(this IQueryable<TSource> queryable, string columnName = "IsDelete") { ... }
// 例:
db.WithoutDeleted();
db.WithoutDeleted("Deleted")` // 可自定义标识删除的列名称
6. 与 FindByIn
类似,用于构建 where {columnName} >= {begin} and {columnName} <= {end}
语句查询数据库
// 会自动处理begin为null或end为null的情况,当同时为null时,返回 where 1=0
IQueryable<TSource> Between<TSource, TKey>(this IQueryable<TSource> queryable, string columnName, TKey begin, TKey end) { ... }
IQueryable<TSource> Between<TSource, TKey>(this IQueryable<TSource> queryable, Expression<Func<TSource, TKey>> selector!!, TKey begin, TKey end) { ... }
// 例:
db.Between("CreateTime", begin, end);
db.Between(x => x.CreateTime, begin, end);
7. 动态构建排序
IOrderedQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, string expr) { ... }
// 例:
db.Where(...).OrderBy("CreateTime desc,Code desc, Id");
PagingExtensions
分页相关扩展方法
1.
PagedList<TSource> Paging<TSource>(this IQueryable<TSource> queryable, int pageIndex, int pageSize, bool returnTotal = true) { ... }
Linq分页
// 例:
query.Paging(1, 20, true);
2. Linq分页
PagedList<TSource> Paging<TSource>(this IQueryable<TSource> queryable, Pager pager, bool returnTotal = true) { ... }
// 例:
query.Paging(Pager.FromLimit(1, 20, "Id desc"), true);
LinqExpressionBuilder
Linq表达式编译程序,基于
ExpressionExtensions;
例1:
var query = db.AsQueryable();
var builder = query.LinqBuidler();
// 构建 list.Where(x => x.Number == number)ToList();
_ = query.Where(builder.Equal("Number", number)).ToList();
// 构建 list.Where(x => new []{1,2,3,4}.Contains(x.Number) )ToList();
_ = query.Where(builder.Equal("Number", new []{1,2,3,4})).ToList();
例2:
var where = builder.NotEqual("IsDelete", true); // 类型会做一些简单规则的转换,比如数据库是int 比较的值是bool
if ( ... )
{
where = builder.And(where, builder.StartsWith("Code", "ORDER_0001"));
}
if ( ... )
{
var begin = DateTime.Today;
var end = DateTime.Today.LastSecondsOfDay();
// Between 会正确处理 begin = null 或 end = null的情况, 但2个同时为null 会返回 x => false
where = builder.And(where, builder.Between("CreateTime", begin, end));
}
if ( ... )
{
where = builder.Not(where);
}
_ = query.Where(where).ToList();
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. |
.NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
.NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
.NET Framework | net45 is compatible. net451 was computed. net452 was computed. net46 was computed. net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
MonoAndroid | monoandroid was computed. |
MonoMac | monomac was computed. |
MonoTouch | monotouch was computed. |
Tizen | tizen40 was computed. tizen60 was computed. |
Xamarin.iOS | xamarinios was computed. |
Xamarin.Mac | xamarinmac was computed. |
Xamarin.TVOS | xamarintvos was computed. |
Xamarin.WatchOS | xamarinwatchos was computed. |
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
-
.NETFramework 4.5
- No dependencies.
-
.NETStandard 2.0
- No dependencies.
NuGet packages (1)
Showing the top 1 NuGet packages that depend on zijian666.AnyExtensions:
Package | Downloads |
---|---|
zijian666.AnyExtensions.ComponentModel
万物皆可扩展 |
GitHub repositories
This package is not used by any popular GitHub repositories.
Version | Downloads | Last updated | |
---|---|---|---|
1.0.15.5 | 47 | 11/20/2024 | |
1.0.15.4 | 134 | 4/12/2024 | |
1.0.15.1 | 110 | 2/1/2024 | |
1.0.15 | 147 | 2/1/2024 | |
1.0.14.1 | 256 | 9/22/2023 | |
1.0.14 | 233 | 9/14/2023 | |
1.0.13 | 145 | 9/13/2023 | |
1.0.12 | 143 | 9/12/2023 | |
1.0.11 | 231 | 7/19/2023 | |
1.0.10 | 427 | 2/2/2023 | |
1.0.9 | 409 | 1/10/2023 | |
1.0.7 | 334 | 1/5/2023 | |
1.0.6 | 624 | 12/15/2022 | |
1.0.5 | 336 | 12/14/2022 | |
1.0.4 | 464 | 12/8/2022 | |
1.0.3 | 700 | 11/24/2022 | |
1.0.2 | 407 | 11/17/2022 | |
1.0.1 | 548 | 11/6/2022 |