You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

1508 lines
48 KiB

/*******************************************************************************
* Copyright © 2017-2020 Znyc.Cloudcar.Admin.Framework 版权所有
* Author: Znyc
* Description: Znyc快速开发平台
* Website:http://www.Znyc.Cloudcar.Admin.com
*********************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;
using System.Xml.Linq;
namespace Znyc.Cloudcar.Admin.Commons.Extensions
{
/// <summary>
/// 对象自定义扩展类
/// </summary>
public static class ObjectExtension
{
private static readonly Regex BoolRegex =
new("(?<info>(true|false))", RegexOptions.IgnoreCase | RegexOptions.Singleline);
private static readonly Regex IntRegex =
new("(?<info>-?\\d+)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
private static readonly Regex DecimalRegex =
new("(?<info>-?\\d+(\\.\\d+)?)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
private static readonly Regex DateTimeRegex = new(
"(?<info>(((\\d+)[/年-](0?[13578]|1[02])[/月-](3[01]|[12]\\d|0?\\d)[日]?)|((\\d+)[/年-](0?[469]|11)[/月-](30|[12]\\d|0?\\d)[日]?)|((\\d+)[/年-]0?2[/月-](2[0-8]|1\\d|0?\\d)[日]?))(\\s((2[0-3]|[0-1]\\d)):[0-5]\\d:[0-5]\\d)?)"
,
RegexOptions.IgnoreCase | RegexOptions.Singleline);
private static readonly Regex TimeSpanRegex =
new(
"(?<info>-?(\\d+\\.(([0-1]\\d)|(2[0-3])):[0-5]\\d:[0-5]\\d)|((([0-1]\\d)|(2[0-3])):[0-5]\\d:[0-5]\\d)|(\\d+))"
,
RegexOptions.IgnoreCase | RegexOptions.Singleline);
private static readonly Regex GuidRegex =
new(
"(?<info>\\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\\}{0,1})"
,
RegexOptions.IgnoreCase | RegexOptions.Singleline);
private static readonly Regex MobileRegex = new("^1[3|4|5|7|8][0-9]\\d{4,8}$");
private static readonly Regex EmailRegex =
new("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$");
/// <summary>
/// 将集合转换为数据集。
/// </summary>
/// <typeparam name="T">转换的元素类型。</typeparam>
/// <param name="list">集合。</param>
/// <param name="generic">是否生成泛型数据集。</param>
/// <returns>数据集。</returns>
public static DataSet ToDataSet<T>(this IEnumerable<T> list, bool generic = true)
{
return ListToDataSet(list, generic);
}
/// <summary>
/// 将集合转换为数据集。
/// </summary>
/// <param name="list">集合。</param>
/// <param name="generic">是否生成泛型数据集。</param>
/// <returns>数据集。</returns>
public static DataSet ToDataSet(this IEnumerable list, bool generic = true)
{
return ListToDataSet(list, generic);
}
/// <summary>
/// 将集合转换为数据集。
/// </summary>
/// <typeparam name="T">转换的元素类型。</typeparam>
/// <param name="list">集合。</param>
/// <param name="generic">是否生成泛型数据集。</param>
/// <returns>数据集。</returns>
public static DataSet ToDataSet<T>(this IEnumerable list, bool generic = true)
{
return ListToDataSet(list, typeof(T), generic);
}
/// <summary>
/// 将实例转换为集合数据集。
/// </summary>
/// <typeparam name="T">实例类型。</typeparam>
/// <param name="o">实例。</param>
/// <param name="generic">是否生成泛型数据集。</param>
/// <returns>数据集。</returns>
public static DataSet ToListSet<T>(this T o, bool generic = true)
{
if (o is IEnumerable)
{
return ListToDataSet(o as IEnumerable, generic);
}
return ListToDataSet(new[] { o }, generic);
}
/// <summary>
/// 将可序列化实例转换为XmlDocument。
/// </summary>
/// <typeparam name="T">实例类型。</typeparam>
/// <param name="o">实例。</param>
/// <returns>XmlDocument。</returns>
public static XmlDocument ToXmlDocument<T>(this T o)
{
XmlDocument xmlDocument = new XmlDocument
{
InnerXml = o.ToListSet().GetXml()
};
return xmlDocument;
}
public static object ChangeType(this object convertibleValue, Type type)
{
if (null == convertibleValue)
{
return null;
}
try
{
if (type == typeof(Guid) || type == typeof(Guid?))
{
string value = convertibleValue.ToString();
if (value == "")
{
return null;
}
return Guid.Parse(value);
}
if (!type.IsGenericType)
{
return Convert.ChangeType(convertibleValue, type);
}
if (type.ToString() == "System.Nullable`1[System.Boolean]" || type.ToString() == "System.Boolean")
{
if (convertibleValue.ToString() == "0")
{
return false;
}
return true;
}
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return Convert.ChangeType(convertibleValue, Nullable.GetUnderlyingType(type));
}
}
catch
{
return null;
}
return null;
}
/// <summary>
/// 获取对象里指定成员名称
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="properties"> 格式 Expression<Func<entityt, object>> exp = x => new { x.字段1, x.字段2 };或x=>x.Name</param>
/// <returns></returns>
public static string[] GetExpressionProperty<TEntity>(this Expression<Func<TEntity, object>> properties)
{
if (properties == null)
{
return new string[] { };
}
if (properties.Body is NewExpression)
{
return ((NewExpression)properties.Body).Members.Select(x => x.Name).ToArray();
}
if (properties.Body is MemberExpression)
{
return new[] { ((MemberExpression)properties.Body).Member.Name };
}
if (properties.Body is UnaryExpression)
{
return new[] { ((properties.Body as UnaryExpression).Operand as MemberExpression).Member.Name };
}
throw new Exception("未实现的表达式");
}
/// <summary>
/// 将集合转换为数据集。
/// </summary>
/// <param name="list">集合。</param>
/// <param name="t">转换的元素类型。</param>
/// <param name="generic">是否生成泛型数据集。</param>
/// <returns>转换后的数据集。</returns>
private static DataSet ListToDataSet(IEnumerable list, Type t, bool generic)
{
DataSet ds = new DataSet("Data");
if (t == null)
{
if (list != null)
{
foreach (object i in list)
{
if (i == null)
{
continue;
}
t = i.GetType();
break;
}
}
if (t == null)
{
return ds;
}
}
ds.Tables.Add(t.Name);
//如果集合中元素为DataSet扩展涉及到的基本类型时,进行特殊转换。
if (t.IsValueType || t == typeof(string))
{
ds.Tables[0].TableName = "Info";
ds.Tables[0].Columns.Add(t.Name);
if (list != null)
{
foreach (object i in list)
{
DataRow addRow = ds.Tables[0].NewRow();
addRow[t.Name] = i;
ds.Tables[0].Rows.Add(addRow);
}
}
return ds;
}
//处理模型的字段和属性。
FieldInfo[] fields = t.GetFields();
PropertyInfo[] properties = t.GetProperties();
foreach (FieldInfo j in fields)
{
if (!ds.Tables[0].Columns.Contains(j.Name))
{
if (generic)
{
ds.Tables[0].Columns.Add(j.Name, j.FieldType);
}
else
{
ds.Tables[0].Columns.Add(j.Name);
}
}
}
foreach (PropertyInfo j in properties)
{
if (!ds.Tables[0].Columns.Contains(j.Name))
{
if (generic)
{
ds.Tables[0].Columns.Add(j.Name, j.PropertyType);
}
else
{
ds.Tables[0].Columns.Add(j.Name);
}
}
}
if (list == null)
{
return ds;
}
//读取list中元素的值。
foreach (object i in list)
{
if (i == null)
{
continue;
}
DataRow addRow = ds.Tables[0].NewRow();
foreach (FieldInfo j in fields)
{
MemberExpression field = Expression.Field(Expression.Constant(i), j.Name);
LambdaExpression lambda = Expression.Lambda(field);
Delegate func = lambda.Compile();
object value = func.DynamicInvoke();
addRow[j.Name] = value;
}
foreach (PropertyInfo j in properties)
{
MemberExpression property = Expression.Property(Expression.Constant(i), j);
LambdaExpression lambda = Expression.Lambda(property);
Delegate func = lambda.Compile();
object value = func.DynamicInvoke();
addRow[j.Name] = value;
}
ds.Tables[0].Rows.Add(addRow);
}
return ds;
}
/// <summary>
/// 将集合转换为数据集。
/// </summary>
/// <typeparam name="T">转换的元素类型。</typeparam>
/// <param name="list">集合。</param>
/// <param name="generic">是否生成泛型数据集。</param>
/// <returns>数据集。</returns>
private static DataSet ListToDataSet<T>(IEnumerable<T> list, bool generic)
{
return ListToDataSet(list, typeof(T), generic);
}
/// <summary>
/// 将集合转换为数据集。
/// </summary>
/// <param name="list">集合。</param>
/// <param name="generic">是否转换为字符串形式。</param>
/// <returns>转换后的数据集。</returns>
private static DataSet ListToDataSet(IEnumerable list, bool generic)
{
return ListToDataSet(list, null, generic);
}
/// <summary>
/// 获取DataSet第一表,第一行,第一列的值。
/// </summary>
/// <param name="ds">DataSet数据集。</param>
/// <returns>值。</returns>
public static object GetData(this DataSet ds)
{
if (
ds == null
|| ds.Tables.Count == 0
)
{
return string.Empty;
}
return ds.Tables[0].GetData();
}
/// <summary>
/// 获取DataTable第一行,第一列的值。
/// </summary>
/// <param name="dt">DataTable数据集表。</param>
/// <returns>值。</returns>
public static object GetData(this DataTable dt)
{
if (
dt.Columns.Count == 0
|| dt.Rows.Count == 0
)
{
return string.Empty;
}
return dt.Rows[0][0];
}
/// <summary>
/// 获取DataSet第一个匹配columnName的值。
/// </summary>
/// <param name="ds">数据集。</param>
/// <param name="columnName">列名。</param>
/// <returns>值。</returns>
public static object GetData(this DataSet ds, string columnName)
{
if (
ds == null
|| ds.Tables.Count == 0
)
{
return string.Empty;
}
foreach (DataTable dt in ds.Tables)
{
object o = dt.GetData(columnName);
if (!string.IsNullOrEmpty(o.ToString()))
{
return o;
}
}
return string.Empty;
}
/// <summary>
/// 获取DataTable第一个匹配columnName的值。
/// </summary>
/// <param name="dt">数据表。</param>
/// <param name="columnName">列名。</param>
/// <returns>值。</returns>
public static object GetData(this DataTable dt, string columnName)
{
if (string.IsNullOrEmpty(columnName))
{
return GetData(dt);
}
if (
dt.Columns.Count == 0
|| dt.Columns.IndexOf(columnName) == -1
|| dt.Rows.Count == 0
)
{
return string.Empty;
}
return dt.Rows[0][columnName];
}
/// <summary>
/// 将object转换为string类型信息。
/// </summary>
/// <param name="o">object。</param>
/// <param name="t">默认值。</param>
/// <returns>string。</returns>
public static string ToString(this object o, string t)
{
string info = string.Empty;
if (o == null)
{
info = t;
}
else
{
info = o.ToString();
}
return info;
}
/// <summary>
/// 将DateTime?转换为string类型信息。
/// </summary>
/// <param name="o">DateTime?。</param>
/// <param name="format">标准或自定义日期和时间格式的字符串。</param>
/// <param name="t">默认值。</param>
/// <returns>string。</returns>
public static string ToString(this DateTime? o, string format, string t)
{
string info = string.Empty;
if (o == null)
{
info = t;
}
else
{
info = o.Value.ToString(format);
}
return info;
}
/// <summary>
/// 将TimeSpan?转换为string类型信息。
/// </summary>
/// <param name="o">TimeSpan?。</param>
/// <param name="format">标准或自定义时间格式的字符串。</param>
/// <param name="t">默认值。</param>
/// <returns>string。</returns>
public static string ToString(this TimeSpan? o, string format, string t)
{
string info = string.Empty;
if (o == null)
{
info = t;
}
else
{
info = o.Value.ToString(format);
}
return info;
}
/// <summary>
/// 将object转换为截取后的string类型信息。
/// </summary>
/// <param name="o">object。</param>
/// <param name="startIndex">此实例中子字符串的起始字符位置(从零开始)。</param>
/// <param name="length">子字符串中的字符数。</param>
/// <param name="suffix">后缀。如果没有截取则不添加。</param>
/// <returns>截取后的string类型信息。</returns>
public static string ToSubString(this object o, int startIndex, int length, string suffix = null)
{
string inputString = o.ToString(string.Empty);
startIndex = Math.Max(startIndex, 0);
startIndex = Math.Min(startIndex, inputString.Length - 1);
length = Math.Max(length, 1);
if (startIndex + length > inputString.Length)
{
length = inputString.Length - startIndex;
}
if (inputString.Length == startIndex + length)
{
return inputString;
}
return inputString.Substring(startIndex, length) + suffix;
}
/// <summary>
/// 将object转换为byte类型信息。
/// </summary>
/// <param name="o">object。</param>
/// <param name="t">默认值。</param>
/// <returns>byte。</returns>
public static byte ToByte(this object o, byte t = default)
{
if (!byte.TryParse(o.ToString(string.Empty), out byte info))
{
info = t;
}
return info;
}
/// <summary>
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static byte[] ToBytes(this object obj)
{
if (obj == null)
{
return null;
}
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
/// <summary>
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static object ToObject(this byte[] source)
{
using (MemoryStream memStream = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
memStream.Write(source, 0, source.Length);
memStream.Seek(0, SeekOrigin.Begin);
object obj = bf.Deserialize(memStream);
return obj;
}
}
/// <summary>
/// 将object转换为char类型信息。
/// </summary>
/// <param name="o">object。</param>
/// <param name="t">默认值。</param>
/// <returns>char。</returns>
public static char ToChar(this object o, char t = default)
{
if (!char.TryParse(o.ToString(string.Empty), out char info))
{
info = t;
}
return info;
}
/// <summary>
/// 将object转换为int类型信息。
/// </summary>
/// <param name="o">object。</param>
/// <param name="t">默认值。</param>
/// <returns>int。</returns>
public static int ToInt(this object o, int t = default)
{
if (!int.TryParse(o.ToString(string.Empty), out int info))
{
info = t;
}
return info;
}
/// <summary>
/// 将object转换为double类型信息。
/// </summary>
/// <param name="o">object。</param>
/// <param name="t">默认值。</param>
/// <returns>double。</returns>
public static double ToDouble(this object o, double t = default)
{
if (!double.TryParse(o.ToString(string.Empty), out double info))
{
info = t;
}
return info;
}
/// <summary>
/// 将object转换为decimal类型信息。
/// </summary>
/// <param name="o">object。</param>
/// <param name="t">默认值。</param>
/// <returns>decimal。</returns>
public static decimal ToDecimal(this object o, decimal t = default)
{
if (!decimal.TryParse(o.ToString(string.Empty), out decimal info))
{
info = t;
}
return info;
}
/// <summary>
/// 将object转换为float类型信息。
/// </summary>
/// <param name="o">object。</param>
/// <param name="t">默认值。</param>
/// <returns>float。</returns>
public static float ToFloat(this object o, float t = default)
{
if (!float.TryParse(o.ToString(string.Empty), out float info))
{
info = t;
}
return info;
}
/// <summary>
/// 将object转换为long类型信息。
/// </summary>
/// <param name="o">object。</param>
/// <param name="t">默认值。</param>
/// <returns>long。</returns>
public static long ToLong(this object o, long t = default)
{
if (!long.TryParse(o.ToString(string.Empty), out long info))
{
info = t;
}
return info;
}
/// <summary>
/// 将object转换为bool类型信息。
/// </summary>
/// <param name="o">object。</param>
/// <param name="t">默认值。</param>
/// <returns>bool。</returns>
public static bool ToBool(this object o, bool t = default)
{
if (!bool.TryParse(o.ToString(string.Empty), out bool info))
{
info = t;
}
return info;
}
/// <summary>
/// 将object转换为sbyte类型信息。
/// </summary>
/// <param name="o">object。</param>
/// <param name="t">默认值。</param>
/// <returns>sbyte。</returns>
public static sbyte ToSbyte(this object o, sbyte t = default)
{
if (!sbyte.TryParse(o.ToString(string.Empty), out sbyte info))
{
info = t;
}
return info;
}
/// <summary>
/// 将object转换为short类型信息。
/// </summary>
/// <param name="o">object。</param>
/// <param name="t">默认值。</param>
/// <returns>short。</returns>
public static short ToShort(this object o, short t = default)
{
if (!short.TryParse(o.ToString(string.Empty), out short info))
{
info = t;
}
return info;
}
/// <summary>
/// 将object转换为ushort类型信息。
/// </summary>
/// <param name="o">object。</param>
/// <param name="t">默认值。</param>
/// <returns>ushort。</returns>
public static ushort ToUShort(this object o, ushort t = default)
{
if (!ushort.TryParse(o.ToString(string.Empty), out ushort info))
{
info = t;
}
return info;
}
/// <summary>
/// 将object转换为ulong类型信息。
/// </summary>
/// <param name="o">object。</param>
/// <param name="t">默认值。</param>
/// <returns>ulong。</returns>
public static ulong ToULong(this object o, ulong t = default)
{
if (!ulong.TryParse(o.ToString(string.Empty), out ulong info))
{
info = t;
}
return info;
}
/// <summary>
/// 将object转换为Enum[T]类型信息。
/// </summary>
/// <param name="o">object。</param>
/// <param name="t">默认值。</param>
/// <returns>Enum[T]。</returns>
public static T ToEnum<T>(this object o, T t = default)
where T : struct
{
if (!Enum.TryParse(o.ToString(string.Empty), out T info))
{
info = t;
}
return info;
}
/// <summary>
/// 将object转换为DateTime类型信息。
/// </summary>
/// <param name="o">object。</param>
/// <param name="t">默认值。</param>
/// <returns>DateTime。</returns>
public static DateTime ToDateTime(this object o, DateTime t = default)
{
if (t == default)
{
t = new DateTime(1753, 1, 1);
}
if (!DateTime.TryParse(o.ToString(string.Empty), out DateTime info))
{
info = t;
}
return info;
}
/// <summary>
/// 将object转换为TimeSpan类型信息。
/// </summary>
/// <param name="o">object。</param>
/// <param name="t">默认值。</param>
/// <returns>TimeSpan。</returns>
public static TimeSpan ToTimeSpan(this object o, TimeSpan t = default)
{
if (t == default)
{
t = new TimeSpan(0, 0, 0);
}
if (!TimeSpan.TryParse(o.ToString(string.Empty), out TimeSpan info))
{
info = t;
}
return info;
}
/// <summary>
/// 将object转换为Guid类型信息。
/// </summary>
/// <param name="o">object。</param>
/// <param name="t">默认值。</param>
/// <returns>Guid。</returns>
public static Guid ToGuid(this object o, Guid t = default)
{
if (!Guid.TryParse(o.ToString(string.Empty), out Guid info))
{
info = t;
}
return info;
}
/// <summary>
/// 从object中获取bool类型信息。
/// </summary>
/// <param name="o">object。</param>
/// <returns>bool。</returns>
public static bool? GetBool(this object o)
{
if (!bool.TryParse(BoolRegex.Match(o.ToString(string.Empty)).Groups["info"].Value, out bool info))
{
return null;
}
return info;
}
/// <summary>
/// 从object中获取int类型信息。
/// </summary>
/// <param name="o">object。</param>
/// <returns>int。</returns>
public static int? GetInt(this object o)
{
if (!int.TryParse(IntRegex.Match(o.ToString(string.Empty)).Groups["info"].Value, out int info))
{
return null;
}
return info;
}
/// <summary>
/// 从object中获取decimal类型信息。
/// </summary>
/// <param name="o">object。</param>
/// <returns>decimal。</returns>
public static decimal? GetDecimal(this object o)
{
if (!decimal.TryParse(DecimalRegex.Match(o.ToString(string.Empty)).Groups["info"].Value, out decimal info))
{
return null;
}
return info;
}
/// <summary>
/// 从object中获取double类型信息。
/// </summary>
/// <param name="o">object。</param>
/// <returns>double。</returns>
public static double? GetDouble(this object o)
{
if (!double.TryParse(DecimalRegex.Match(o.ToString(string.Empty)).Groups["info"].Value, out double info))
{
return null;
}
return info;
}
/// <summary>
/// 从object中获取正数信息。
/// </summary>
/// <param name="o">object。</param>
/// <returns>decimal。</returns>
public static decimal? GetPositiveNumber(this object o)
{
if (!decimal.TryParse(DecimalRegex.Match(o.ToString(string.Empty)).Groups["info"].Value, out decimal info))
{
return null;
}
return Math.Abs(info);
}
/// <summary>
/// 从object中获取DateTime?类型信息。
/// </summary>
/// <param name="o">object。</param>
/// <returns>DateTime?。</returns>
public static DateTime? GetDateTime(this object o)
{
if (!DateTime.TryParse(
DateTimeRegex.Match(o.ToString(string.Empty)).Groups["info"].Value.Replace("年", "-").Replace("月", "-")
.Replace("/", "-").Replace("日", ""), out DateTime info))
{
return null;
}
return info;
}
/// <summary>
/// 从object中获取TimeSpan?类型信息。
/// </summary>
/// <param name="o">object。</param>
/// <returns>TimeSpan?。</returns>
public static TimeSpan? GetTimeSpan(this object o)
{
if (!TimeSpan.TryParse(TimeSpanRegex.Match(o.ToString(string.Empty)).Groups["info"].Value, out TimeSpan info))
{
return null;
}
return info;
}
/// <summary>
/// 从object中获取Guid?类型信息。
/// </summary>
/// <param name="o">object。</param>
/// <returns>Guid?。</returns>
public static Guid? GetGuid(this object o)
{
if (!Guid.TryParse(GuidRegex.Match(o.ToString(string.Empty)).Groups["info"].Value, out Guid info))
{
return null;
}
return info;
}
/// <summary>
/// 将object转换为SqlServer中的DateTime?类型信息。
/// </summary>
/// <param name="o">object。</param>
/// <param name="t">默认值。</param>
/// <returns>DateTime?。</returns>
public static DateTime? GetSqlDateTime(this object o, DateTime t = default)
{
if (!DateTime.TryParse(o.ToString(string.Empty), out DateTime info))
{
info = t;
}
if (info < new DateTime(1753, 1, 1) || info > new DateTime(9999, 12, 31))
{
return null;
}
return info;
}
/// <summary>
/// 读取XElement节点的文本内容。
/// </summary>
/// <param name="xElement">XElement节点。</param>
/// <param name="t">默认值。</param>
/// <returns>文本内容。</returns>
public static string Value(this XElement xElement, string t = default)
{
if (xElement == null)
{
return t;
}
return xElement.Value;
}
/// <summary>
/// 获取与指定键相关的值。
/// </summary>
/// <typeparam name="TKey">键类型。</typeparam>
/// <typeparam name="TValue">值类型。</typeparam>
/// <param name="dictionary">表示键/值对象的泛型集合。</param>
/// <param name="key">键。</param>
/// <param name="t">默认值。</param>
/// <returns>值。</returns>
public static TValue GetValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key,
TValue t = default)
{
if (dictionary == null || key == null)
{
return t;
}
if (!dictionary.TryGetValue(key, out TValue value))
{
value = t;
}
return value;
}
/// <summary>
/// 获取与指定键相关或者第一个的值。
/// </summary>
/// <typeparam name="TKey">键类型。</typeparam>
/// <typeparam name="TValue">值类型。</typeparam>
/// <param name="dictionary">表示键/值对象的泛型集合。</param>
/// <param name="key">键。</param>
/// <param name="t">默认值。</param>
/// <returns>值。</returns>
public static TValue GetFirstOrDefaultValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key,
TValue t = default)
{
if (dictionary == null || key == null)
{
return t;
}
if (!dictionary.TryGetValue(key, out TValue value))
{
if (dictionary.Count() == 0)
{
value = t;
}
else
{
value = dictionary.FirstOrDefault().Value;
}
}
return value;
}
/// <summary>
/// 获取具有指定 System.Xml.Linq.XName 的第一个(按文档顺序)子元素。
/// </summary>
/// <param name="xContainer">XContainer。</param>
/// <param name="xName">要匹配的 System.Xml.Linq.XName。</param>
/// <param name="t">是否返回同名默认值。</param>
/// <returns>与指定 System.Xml.Linq.XName 匹配的 System.Xml.Linq.XElement,或者为 null。</returns>
public static XElement Element(this XContainer xContainer, XName xName, bool t)
{
XElement info;
if (xContainer == null)
{
info = null;
}
else
{
info = xContainer.Element(xName);
}
if (t && info == null)
{
info = new XElement(xName);
}
return info;
}
/// <summary>
/// 按文档顺序返回此元素或文档的子元素集合。
/// </summary>
/// <param name="xContainer">XContainer。</param>
/// <param name="t">是否返回非空默认值。</param>
/// <returns>System.Xml.Linq.XElement 的按文档顺序包含此System.Xml.Linq.XContainer 的子元素,或者非空默认值。</returns>
public static IEnumerable<XElement> Elements(this XContainer xContainer, bool t)
{
IEnumerable<XElement> info;
if (xContainer == null)
{
info = null;
}
else
{
info = xContainer.Elements();
}
if (t && info == null)
{
info = new List<XElement>();
}
return info;
}
/// <summary>
/// 按文档顺序返回此元素或文档的经过筛选的子元素集合。集合中只包括具有匹配 System.Xml.Linq.XName 的元素。
/// </summary>
/// <param name="xContainer">XContainer。</param>
/// <param name="xName">要匹配的 System.Xml.Linq.XName。</param>
/// <param name="t">是否返回非空默认值。</param>
/// <returns>System.Xml.Linq.XElement 的按文档顺序包含具有匹配System.Xml.Linq.XName 的 System.Xml.Linq.XContainer 的子级,或者非空默认值。</returns>
public static IEnumerable<XElement> Elements(this XContainer xContainer, XName xName, bool t)
{
IEnumerable<XElement> info;
if (xContainer == null)
{
info = null;
}
else
{
info = xContainer.Elements(xName);
}
if (t && info == null)
{
info = new List<XElement>();
}
return info;
}
/// <summary>
/// 删除html标签。
/// </summary>
/// <param name="html">输入的字符串。</param>
/// <returns>没有html标签的字符串。</returns>
public static string RemoveHTMLTags(this string html)
{
return Regex
.Replace(
Regex.Replace(
Regex.Replace(
(html ?? string.Empty).Replace("&nbsp;", " ").Replace("\r\n", " ").Replace("\n", " ")
.Replace("\r", " ").Replace("\t", " "), "<\\/?[^>]+>", "\r\n"), "(\r\n)+", "\r\n"),
"(\\s)+", " ").Trim();
}
/// <summary>
/// 字符串转换为文件名。
/// </summary>
/// <param name="s">字符串。</param>
/// <returns>文件名。</returns>
public static string ToFileName(this string s)
{
return Regex.Replace(s.ToString(string.Empty), @"[\\/:*?<>|]", "_").Replace("\t", " ").Replace("\r\n", " ")
.Replace("\"", " ");
}
/// <summary>
/// 获取星期一的日期。
/// </summary>
/// <param name="dateTime">日期。</param>
/// <returns>星期一的日期。</returns>
public static DateTime? GetMonday(this DateTime dateTime)
{
return dateTime.AddDays(-1 * (int)dateTime.AddDays(-1).DayOfWeek).ToString("yyyy-MM-dd").GetDateTime();
}
/// <summary>
/// 获取默认非空字符串。
/// </summary>
/// <param name="s">首选默认非空字符串。</param>
/// <param name="args">依次非空字符串可选项。</param>
/// <returns>默认非空字符串。若无可选项则返回string.Empty。</returns>
public static string DefaultStringIfEmpty(this string s, params string[] args)
{
if (string.IsNullOrEmpty(s))
{
foreach (string i in args)
{
if (!string.IsNullOrEmpty(i) && !string.IsNullOrEmpty(i.Trim()))
{
return i;
}
}
}
return s ?? string.Empty;
}
/// <summary>
/// 对 URL 字符串进行编码。
/// </summary>
/// <param name="s">要编码的文本。</param>
/// <param name="regex">匹配要编码的文本。</param>
/// <param name="encoding">指定编码方案的 System.Text.Encoding 对象。</param>
/// <returns>一个已编码的字符串。</returns>
public static string ToUrlEncodeString(this string s, Regex regex = default, Encoding encoding = null)
{
if (encoding == null)
{
encoding = Encoding.UTF8;
}
if (regex == null)
{
return HttpUtility.UrlEncode(s, encoding);
}
List<string> l = new List<string>();
foreach (char i in s)
{
string t = i.ToString();
l.Add(regex.IsMatch(t) ? HttpUtility.UrlEncode(t, encoding) : t);
}
return string.Join(string.Empty, l);
}
/// <summary>
/// 对 URL 字符串进行编码。
/// </summary>
/// <param name="s">要编码的文本。</param>
/// <param name="regex">匹配要编码的文本。</param>
/// <param name="encoding">指定编码方案的 System.Text.Encoding 对象。</param>
/// <returns>一个已编码的字符串。</returns>
public static string ToUrlEncodeString(this string s, string regex, Encoding encoding = null)
{
return ToUrlEncodeString(s, new Regex(regex), encoding);
}
/// <summary>
/// 将日期转换为UNIX时间戳字符串
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
public static string ToUnixTimeStamp(this DateTime date)
{
DateTime startTime = TimeZoneInfo.ConvertTimeToUtc(new DateTime(1970, 1, 1));
string timeStamp = date.Subtract(startTime).Ticks.ToString();
return timeStamp.Substring(0, timeStamp.Length - 7);
}
public static string Join(this IEnumerable<object> source, string separator)
{
return string.Join(separator, source);
}
/// <summary>
/// 判断当前字符串是否是移动电话号码
/// </summary>
/// <param name="mobile"></param>
/// <returns></returns>
public static bool IsMobile(this string mobile)
{
return MobileRegex.IsMatch(mobile);
}
/// <summary>
/// 判断当前字符串是否为邮箱
/// </summary>
/// <param name="email"></param>
/// <returns></returns>
public static bool IsEmail(this string email)
{
return EmailRegex.IsMatch(email);
}
/// <summary>
/// 把对象类型转换为指定类型
/// </summary>
/// <param name="value"></param>
/// <param name="conversionType"></param>
/// <returns></returns>
public static object CastTo(this object value, Type conversionType)
{
if (value == null)
{
return null;
}
if (conversionType.IsNullableType())
{
conversionType = conversionType.GetUnNullableType();
}
if (conversionType.IsEnum)
{
return Enum.Parse(conversionType, value.ToString());
}
if (conversionType == typeof(Guid))
{
return Guid.Parse(value.ToString());
}
return Convert.ChangeType(value, conversionType);
}
/// <summary>
/// 把对象类型转化为指定类型
/// </summary>
/// <typeparam name="T"> 动态类型 </typeparam>
/// <param name="value"> 要转化的源对象 </param>
/// <returns> 转化后的指定类型的对象,转化失败引发异常。 </returns>
public static T CastTo<T>(this object value)
{
if (value == null && default(T) == null)
{
return default;
}
if (value.GetType() == typeof(T))
{
return (T)value;
}
object result = CastTo(value, typeof(T));
return (T)result;
}
/// <summary>
/// 把对象类型转化为指定类型,转化失败时返回指定的默认值
/// </summary>
/// <typeparam name="T"> 动态类型 </typeparam>
/// <param name="value"> 要转化的源对象 </param>
/// <param name="defaultValue"> 转化失败返回的指定默认值 </param>
/// <returns> 转化后的指定类型对象,转化失败时返回指定的默认值 </returns>
public static T CastTo<T>(this object value, T defaultValue)
{
try
{
return CastTo<T>(value);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// 将对象保存为csv
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="csvFullName">文件名称</param>
/// <param name="separator">分隔符,默认逗号</param>
public static void SaveToCsv<T>(this IEnumerable<T> source, string csvFullName, string separator = ",")
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (string.IsNullOrEmpty(separator))
{
separator = ",";
}
string csv = string.Join(separator, source);
using (StreamWriter sw = new StreamWriter(csvFullName, false))
{
sw.Write(csv);
sw.Close();
}
}
public static bool IsImplement(this Type entityType, Type interfaceType)
{
return /*entityType.IsClass && !entityType.IsAbstract &&*/ entityType.GetTypeInfo().GetInterfaces().Any(t =>
t.GetTypeInfo().IsGenericType && t.GetGenericTypeDefinition() == interfaceType);
}
/// <summary>
/// 将对象转为DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static DataTable ToDataTable<T>(this IEnumerable<T> source)
{
DataTable dtReturn = new DataTable();
if (source == null)
{
return dtReturn;
}
// column names
PropertyInfo[] oProps = null;
foreach (T rec in source)
{
// Use reflection to get property names, to create table, Only first time, others will follow
if (oProps == null)
{
oProps = rec.GetType().GetProperties();
foreach (PropertyInfo pi in oProps)
{
Type colType = pi.PropertyType;
if (colType.IsNullableType())
{
colType = colType.GetGenericArguments()[0];
}
if (colType == typeof(bool))
{
colType = typeof(int);
}
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
}
DataRow dr = dtReturn.NewRow();
foreach (PropertyInfo pi in oProps)
{
object value = pi.GetValue(rec, null) ?? DBNull.Value;
if (value is bool)
{
dr[pi.Name] = (bool)value ? 1 : 0;
}
else
{
dr[pi.Name] = value;
}
}
dtReturn.Rows.Add(dr);
}
return dtReturn;
}
}
/// <summary>
/// 结果。
/// </summary>
/// <typeparam name="T">结果返回值类型。</typeparam>
public class Result<T>
{
/// <summary>
/// 标记。
/// </summary>
public Flag Flag { get; set; }
/// <summary>
/// 返回值。
/// </summary>
public T Return { get; set; }
/// <summary>
/// 消息。
/// </summary>
public string Message { get; set; }
/// <summary>
/// 异常。
/// </summary>
public Exception Exception { get; set; }
/// <summary>
/// 时间。
/// </summary>
public DateTime DateTime { get; set; }
/// <summary>
/// 整型数据。
/// </summary>
public int Int { get; set; }
/// <summary>
/// 浮点数据。
/// </summary>
public decimal Decimal { get; set; }
/// <summary>
/// 布尔数据。
/// </summary>
public bool Bool { get; set; }
/// <summary>
/// 对象。
/// </summary>
public object Object { get; set; }
}
/// <summary>
/// 标记。
/// </summary>
public enum Flag
{
/// <summary>
/// 默认。
/// </summary>
Default,
/// <summary>
/// 真。
/// </summary>
True,
/// <summary>
/// 假。
/// </summary>
False
}
}