懒得勤快 2 years ago
parent
commit
267493b84a

+ 21 - 47
Masuit.Tools.Abstractions/Extensions/BaseType/IEnumerableExtensions.cs

@@ -66,10 +66,9 @@ public static class IEnumerableExtensions
     private static IEnumerable<TSource> IntersectByIterator<TSource, TKey>(IEnumerable<TSource> first, IEnumerable<TSource> second, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
     {
         var set = new HashSet<TKey>(second.Select(keySelector), comparer);
-        foreach (var source in first)
+        foreach (var item in first.Where(source => set.Remove(keySelector(source))))
         {
-            if (set.Remove(keySelector(source)))
-                yield return source;
+            yield return item;
         }
     }
 
@@ -153,13 +152,7 @@ public static class IEnumerableExtensions
         if (source == null) throw new ArgumentNullException(nameof(source));
         if (keySelector == null) throw new ArgumentNullException(nameof(keySelector));
         var set = new HashSet<TKey>();
-        foreach (var item in source)
-        {
-            if (set.Add(keySelector(item)))
-            {
-                yield return item;
-            }
-        }
+        return source.Where(item => set.Add(keySelector(item)));
     }
 
     /// <summary>
@@ -197,11 +190,7 @@ public static class IEnumerableExtensions
     private static IEnumerable<TSource> IntersectByIterator<TSource, TKey>(IEnumerable<TSource> first, IEnumerable<TKey> second, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
     {
         var set = new HashSet<TKey>(second, comparer);
-        foreach (var source in first)
-        {
-            if (set.Remove(keySelector(source)))
-                yield return source;
-        }
+        return first.Where(source => set.Remove(keySelector(source)));
     }
 
     /// <summary>
@@ -240,11 +229,7 @@ public static class IEnumerableExtensions
     private static IEnumerable<TSource> ExceptByIterator<TSource, TKey>(IEnumerable<TSource> first, IEnumerable<TKey> second, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
     {
         var set = new HashSet<TKey>(second, comparer);
-        foreach (var source in first)
-        {
-            if (set.Add(keySelector(source)))
-                yield return source;
-        }
+        return first.Where(source => set.Add(keySelector(source)));
     }
 
 #endif
@@ -314,12 +299,9 @@ public static class IEnumerableExtensions
     /// <param name="values"></param>
     public static void AddRangeIf<T>(this ICollection<T> @this, Func<T, bool> predicate, params T[] values)
     {
-        foreach (var obj in values)
+        foreach (var obj in values.Where(predicate))
         {
-            if (predicate(obj))
-            {
-                @this.Add(obj);
-            }
+            @this.Add(obj);
         }
     }
 
@@ -332,12 +314,9 @@ public static class IEnumerableExtensions
     /// <param name="values"></param>
     public static void AddRangeIf<T>(this ConcurrentBag<T> @this, Func<T, bool> predicate, params T[] values)
     {
-        foreach (var obj in values)
+        foreach (var obj in values.Where(predicate))
         {
-            if (predicate(obj))
-            {
-                @this.Add(obj);
-            }
+            @this.Add(obj);
         }
     }
 
@@ -350,12 +329,9 @@ public static class IEnumerableExtensions
     /// <param name="values"></param>
     public static void AddRangeIf<T>(this ConcurrentQueue<T> @this, Func<T, bool> predicate, params T[] values)
     {
-        foreach (var obj in values)
+        foreach (var obj in values.Where(predicate))
         {
-            if (predicate(obj))
-            {
-                @this.Enqueue(obj);
-            }
+            @this.Enqueue(obj);
         }
     }
 
@@ -399,19 +375,19 @@ public static class IEnumerableExtensions
     /// <param name="value">值</param>
     public static void InsertAfter<T>(this IList<T> list, Func<T, bool> condition, T value)
     {
-        foreach (var item in list.Select((item, index) => new
+        foreach (var index in list.Select((item, index) => new
         {
             item,
             index
-        }).Where(p => condition(p.item)).OrderByDescending(p => p.index))
+        }).Where(p => condition(p.item)).OrderByDescending(p => p.index).Select(t => t.index))
         {
-            if (item.index + 1 == list.Count)
+            if (index + 1 == list.Count)
             {
                 list.Add(value);
             }
             else
             {
-                list.Insert(item.index + 1, value);
+                list.Insert(index + 1, value);
             }
         }
     }
@@ -425,19 +401,19 @@ public static class IEnumerableExtensions
     /// <param name="value">值</param>
     public static void InsertAfter<T>(this IList<T> list, int index, T value)
     {
-        foreach (var item in list.Select((v, i) => new
+        foreach (var i in list.Select((v, i) => new
         {
             Value = v,
             Index = i
-        }).Where(p => p.Index == index).OrderByDescending(p => p.Index))
+        }).Where(p => p.Index == index).OrderByDescending(p => p.Index).Select(t => t.Index))
         {
-            if (item.Index + 1 == list.Count)
+            if (i + 1 == list.Count)
             {
                 list.Add(value);
             }
             else
             {
-                list.Insert(item.Index + 1, value);
+                list.Insert(i + 1, value);
             }
         }
     }
@@ -452,9 +428,7 @@ public static class IEnumerableExtensions
     /// <returns></returns>
     public static HashSet<TResult> ToHashSet<T, TResult>(this IEnumerable<T> source, Func<T, TResult> selector)
     {
-        var set = new HashSet<TResult>();
-        set.UnionWith(source.Select(selector));
-        return set;
+        return new HashSet<TResult>(source.Select(selector));
     }
 
     /// <summary>
@@ -865,7 +839,7 @@ public static class IEnumerableExtensions
     {
         double result = 0;
         var list = source as ICollection<double> ?? source.ToList();
-        int count = list.Count();
+        int count = list.Count;
         if (count > 1)
         {
             var avg = list.Average();

+ 1 - 1
Masuit.Tools.AspNetCore/Masuit.Tools.AspNetCore.csproj

@@ -44,7 +44,7 @@
     </ItemGroup>
 
     <ItemGroup>
-      <PackageReference Include="FastExpressionCompiler" Version="4.0.0" />
+      <PackageReference Include="FastExpressionCompiler" Version="4.0.1" />
       <PackageReference Include="System.Net.Http.Json" Version="8.0" />
     </ItemGroup>
 

+ 131 - 136
Masuit.Tools.AspNetCore/ModelBinder/ModelBindingContextExtension.cs

@@ -10,150 +10,145 @@ namespace Masuit.Tools.AspNetCore.ModelBinder;
 
 internal static class ModelBindingContextExtension
 {
-	/// <summary>
-	/// 获取绑定参数对应的 Attribute
-	/// </summary>
-	/// <typeparam name="T">Attribute对象</typeparam>
-	/// <param name="bindingContext">绑定参数上下文</param>
-	/// <param name="parameterName">参数名称</param>
-	/// <returns></returns>
-	public static T GetAttribute<T>(this ModelBindingContext bindingContext, string parameterName = null) where T : Attribute
-	{
-		var fieldName = parameterName ?? bindingContext.FieldName;
-		var ctrlActionDesc = bindingContext.ActionContext.ActionDescriptor as ControllerActionDescriptor;
-		var fieldParameter = ctrlActionDesc!.MethodInfo.GetParameters().Single(p => p.Name == fieldName);
-		return fieldParameter.GetCustomAttributes(typeof(T), false).Single() as T;
-	}
+    /// <summary>
+    /// 获取绑定参数对应的 Attribute
+    /// </summary>
+    /// <typeparam name="T">Attribute对象</typeparam>
+    /// <param name="bindingContext">绑定参数上下文</param>
+    /// <param name="parameterName">参数名称</param>
+    /// <returns></returns>
+    public static T GetAttribute<T>(this ModelBindingContext bindingContext, string parameterName = null) where T : Attribute
+    {
+        var fieldName = parameterName ?? bindingContext.FieldName;
+        var ctrlActionDesc = bindingContext.ActionContext.ActionDescriptor as ControllerActionDescriptor;
+        var fieldParameter = ctrlActionDesc!.MethodInfo.GetParameters().Single(p => p.Name == fieldName);
+        return fieldParameter.GetCustomAttributes(typeof(T), false).Single() as T;
+    }
 
-	/// <summary>
-	/// 判断该次请求体Body是否是Json内容类型
-	/// </summary>
-	/// <param name="httpContext"></param>
-	/// <param name="charSet"></param>
-	/// <returns></returns>
-	public static bool IsJsonContent(this HttpContext httpContext, out string charSet)
-	{
-		string strContentType = httpContext.Request.ContentType;
-		if (string.IsNullOrEmpty(strContentType))
-		{
-			charSet = null;
-			return false;
-		}
+    /// <summary>
+    /// 判断该次请求体Body是否是Json内容类型
+    /// </summary>
+    /// <param name="httpContext"></param>
+    /// <param name="charSet"></param>
+    /// <returns></returns>
+    public static bool IsJsonContent(this HttpContext httpContext, out string charSet)
+    {
+        string strContentType = httpContext.Request.ContentType;
+        if (string.IsNullOrEmpty(strContentType))
+        {
+            charSet = null;
+            return false;
+        }
 
-		var contentType = new ContentType(strContentType);
-		charSet = contentType.CharSet;
-		return contentType.MediaType.ToLower() == "application/json";
-	}
+        var contentType = new ContentType(strContentType);
+        charSet = contentType.CharSet;
+        return contentType.MediaType.ToLower() == "application/json";
+    }
 
-	/// <summary>
-	/// 获取请求体Body字符串内容
-	/// </summary>
-	/// <param name="context"></param>
-	/// <param name="encoding"></param>
-	/// <returns></returns>
-	public static string GetBodyString(this HttpContext context, Encoding encoding)
-	{
-		context.Request.EnableBuffering(); //Ensure the HttpRequest.Body can be read multipletimes
-		int contentLen = 255;
-		if (context.Request.ContentLength != null)
-		{
-			contentLen = (int)context.Request.ContentLength;
-		}
+    /// <summary>
+    /// 获取请求体Body字符串内容
+    /// </summary>
+    /// <param name="context"></param>
+    /// <param name="encoding"></param>
+    /// <returns></returns>
+    public static string GetBodyString(this HttpContext context, Encoding encoding)
+    {
+        context.Request.EnableBuffering(); //Ensure the HttpRequest.Body can be read multipletimes
+        int contentLen = 255;
+        if (context.Request.ContentLength != null)
+        {
+            contentLen = (int)context.Request.ContentLength;
+        }
 
-		var body = context.Request.Body;
-		string bodyText;
-		if (contentLen <= 0)
-		{
-			bodyText = "";
-		}
-		else
-		{
-			using var reader = new StreamReader(body, encoding, true, contentLen, true);
-			bodyText = reader.ReadToEndAsync().Result;
-		}
+        var body = context.Request.Body;
+        string bodyText;
+        if (contentLen <= 0)
+        {
+            bodyText = "";
+        }
+        else
+        {
+            using var reader = new StreamReader(body, encoding, true, contentLen, true);
+            bodyText = reader.ReadToEndAsync().Result;
+        }
 
-		body.Position = 0;
-		return bodyText;
-	}
+        body.Position = 0;
+        return bodyText;
+    }
 
-	/// <summary>
-	/// 尝试设置默认值
-	/// </summary>
-	/// <param name="bindingContext"></param>
-	public static bool TrySetDefaultValue(this ModelBindingContext bindingContext)
-	{
-		var attr = bindingContext.GetAttribute<FromBodyOrDefaultAttribute>();
-		if (attr.DefaultValue != null)
-		{
-			var targetValue = attr.DefaultValue.ChangeType(bindingContext.ModelType);
-			bindingContext.Result = ModelBindingResult.Success(targetValue);
-			return true;
-		}
+    /// <summary>
+    /// 尝试设置默认值
+    /// </summary>
+    /// <param name="bindingContext"></param>
+    public static bool TrySetDefaultValue(this ModelBindingContext bindingContext)
+    {
+        var attr = bindingContext.GetAttribute<FromBodyOrDefaultAttribute>();
+        if (attr.DefaultValue != null)
+        {
+            var targetValue = attr.DefaultValue.ChangeType(bindingContext.ModelType);
+            bindingContext.Result = ModelBindingResult.Success(targetValue);
+            return true;
+        }
 
-		return false;
-	}
+        return false;
+    }
 
-	/// <summary>
-	/// 转换为对应类型
-	/// </summary>
-	/// <param name="this"></param>
-	public static T ConvertObjectTo<T>(this object @this)
-	{
-		return (T)ConvertObject(@this, typeof(T));
-	}
+    /// <summary>
+    /// 转换为对应类型
+    /// </summary>
+    /// <param name="this"></param>
+    public static T ConvertObjectTo<T>(this object @this)
+    {
+        return (T)ConvertObject(@this, typeof(T));
+    }
 
-	/// <summary>
-	/// 转换为对应类型
-	/// </summary>
-	/// <param name="this"></param>
-	/// <param name="type"></param>
-	public static object ConvertObject(this object @this, Type type)
-	{
-		object value;
-		if (@this is string str)
-		{
-			str = str.Trim();
-			if ((str.StartsWith("[") && str.EndsWith("]")) || str.StartsWith("{") && str.EndsWith("}"))
-			{
-				value = JsonConvert.DeserializeObject(str, type);
-			}
-			else if ((str.StartsWith("\"[") && str.EndsWith("]\"")) || str.StartsWith("\"{") && str.EndsWith("}\""))
-			{
-				// json字符串 又被 json序列化 的情况
-				var objects = JsonConvert.DeserializeObject(str);
-				value = JsonConvert.SerializeObject(objects).ConvertObject(type);
-			}
-			else
-			{
-				var text = JsonConvert.SerializeObject(@this);
-				value = JsonConvert.DeserializeObject(text, type);
-			}
-		}
-		else if (@this is StringValues values)
-		{
-			var text = values.ToString();
-			if (type.IsSimpleArrayType() || type.IsSimpleListType())
-			{
-				text = JsonConvert.SerializeObject(values);
-				value = JsonConvert.DeserializeObject(text, type);
-			}
-			else
-			{
-				text = JsonConvert.SerializeObject(text);
-				value = JsonConvert.DeserializeObject(text, type);
-			}
-		}
-		else if (@this is JToken)
-		{
-			var text = JsonConvert.SerializeObject(@this);
-			value = JsonConvert.DeserializeObject(text, type);
-		}
-		else
-		{
-			var text = JsonConvert.SerializeObject(@this);
-			value = JsonConvert.DeserializeObject(text, type);
-		}
+    /// <summary>
+    /// 转换为对应类型
+    /// </summary>
+    /// <param name="this"></param>
+    /// <param name="type"></param>
+    public static object ConvertObject(this object @this, Type type)
+    {
+        object value;
+        if (@this is string str)
+        {
+            str = str.Trim();
+            if ((str.StartsWith('[') && str.EndsWith(']')) || str.StartsWith('{') && str.EndsWith('}'))
+            {
+                value = JsonConvert.DeserializeObject(str, type);
+            }
+            else if ((str.StartsWith("\"[") && str.EndsWith("]\"")) || str.StartsWith("\"{") && str.EndsWith("}\""))
+            {
+                // json字符串 又被 json序列化 的情况
+                var objects = JsonConvert.DeserializeObject(str);
+                value = JsonConvert.SerializeObject(objects).ConvertObject(type);
+            }
+            else
+            {
+                var text = JsonConvert.SerializeObject(@this);
+                value = JsonConvert.DeserializeObject(text, type);
+            }
+        }
+        else if (@this is StringValues values)
+        {
+            var text = values.ToString();
+            if (type.IsSimpleArrayType() || type.IsSimpleListType())
+            {
+                text = JsonConvert.SerializeObject(values);
+                value = JsonConvert.DeserializeObject(text, type);
+            }
+            else
+            {
+                text = JsonConvert.SerializeObject(text);
+                value = JsonConvert.DeserializeObject(text, type);
+            }
+        }
+        else
+        {
+            var text = JsonConvert.SerializeObject(@this);
+            value = JsonConvert.DeserializeObject(text, type);
+        }
 
-		return value;
-	}
+        return value;
+    }
 }

+ 1 - 1
Masuit.Tools.Excel/Masuit.Tools.Excel.csproj

@@ -38,7 +38,7 @@
       </None>
     </ItemGroup>
     <ItemGroup>
-        <PackageReference Include="EPPlus" Version="7.0.1" />
+        <PackageReference Include="EPPlus" Version="7.0.2" />
         <PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0" PrivateAssets="All" />
     </ItemGroup>
     <ItemGroup>