CommonFun.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  1. using MathNet.Numerics.Statistics;
  2. using Newtonsoft.Json;
  3. using Newtonsoft.Json.Linq;
  4. using OASystem.Domain.ViewModels.Groups;
  5. using System.Collections;
  6. using System.Globalization;
  7. using System.Reflection;
  8. using TinyPinyin;
  9. namespace OASystem.Infrastructure.Tools;
  10. /// <summary>
  11. /// 工具类
  12. /// </summary>
  13. public static class CommonFun
  14. {
  15. public static string GUID => Guid.NewGuid().ToString("N");
  16. public static bool IsNull(this string s)
  17. {
  18. return string.IsNullOrWhiteSpace(s);
  19. }
  20. public static bool NotNull(this string s)
  21. {
  22. return !string.IsNullOrWhiteSpace(s);
  23. }
  24. public static int GetRandom(int minNum, int maxNum)
  25. {
  26. var seed = BitConverter.ToInt32(Guid.NewGuid().ToByteArray(), 0);
  27. return new Random(seed).Next(minNum, maxNum);
  28. }
  29. public static string GetSerialNumber(string prefix = "")
  30. {
  31. return prefix + DateTime.Now.ToString("yyyyMMddHHmmssfff") + GetRandom(1000, 9999).ToString();
  32. }
  33. public static string ToJson(this object obj)
  34. {
  35. return System.Text.Json.JsonSerializer.Serialize(obj);
  36. }
  37. public static T ToObject<T>(this string json)
  38. {
  39. return System.Text.Json.JsonSerializer.Deserialize<T>(json);
  40. }
  41. public static object GetDefaultVal(string typename)
  42. {
  43. return typename switch
  44. {
  45. "Boolean" => false,
  46. "DateTime" => default(DateTime),
  47. "Date" => default(DateTime),
  48. "Double" => 0.0,
  49. "Single" => 0f,
  50. "Int32" => 0,
  51. "String" => string.Empty,
  52. "Decimal" => 0m,
  53. _ => null,
  54. };
  55. }
  56. public static void CoverNull<T>(T model) where T : class
  57. {
  58. if (model == null)
  59. {
  60. return;
  61. }
  62. var typeFromHandle = typeof(T);
  63. var properties = typeFromHandle.GetProperties();
  64. var array = properties;
  65. for (var i = 0; i < array.Length; i++)
  66. {
  67. var propertyInfo = array[i];
  68. if (propertyInfo.GetValue(model, null) == null)
  69. {
  70. propertyInfo.SetValue(model, GetDefaultVal(propertyInfo.PropertyType.Name), null);
  71. }
  72. }
  73. }
  74. public static void CoverNull<T>(List<T> models) where T : class
  75. {
  76. if (models.Count == 0)
  77. {
  78. return;
  79. }
  80. foreach (var model in models)
  81. {
  82. CoverNull(model);
  83. }
  84. }
  85. public static bool ToBool(this object thisValue, bool errorvalue = false)
  86. {
  87. if (thisValue != null && thisValue != DBNull.Value && bool.TryParse(thisValue.ToString(), out bool reval))
  88. {
  89. return reval;
  90. }
  91. return errorvalue;
  92. }
  93. #region 文件操作
  94. public static FileInfo[] GetFiles(string directoryPath)
  95. {
  96. if (!IsExistDirectory(directoryPath))
  97. {
  98. throw new DirectoryNotFoundException();
  99. }
  100. var root = new DirectoryInfo(directoryPath);
  101. return root.GetFiles();
  102. }
  103. public static bool IsExistDirectory(string directoryPath)
  104. {
  105. return Directory.Exists(directoryPath);
  106. }
  107. public static string ReadFile(string Path)
  108. {
  109. string s;
  110. if (!File.Exists(Path))
  111. s = "不存在相应的目录";
  112. else
  113. {
  114. var f2 = new StreamReader(Path, Encoding.Default);
  115. s = f2.ReadToEnd();
  116. f2.Close();
  117. f2.Dispose();
  118. }
  119. return s;
  120. }
  121. public static void FileMove(string OrignFile, string NewFile)
  122. {
  123. File.Move(OrignFile, NewFile);
  124. }
  125. public static void CreateDir(string dir)
  126. {
  127. if (dir.Length == 0) return;
  128. if (!Directory.Exists(dir))
  129. Directory.CreateDirectory(dir);
  130. }
  131. /// <summary>
  132. /// 验证文件名称
  133. /// </summary>
  134. /// <param name="fileName"></param>
  135. /// <returns></returns>
  136. public static string ValidFileName(string fileName)
  137. {
  138. if (string.IsNullOrEmpty(fileName)) return Guid.NewGuid().ToString();
  139. // 获取非法文件名字符
  140. char[] invalidChars = Path.GetInvalidFileNameChars();
  141. return new string(fileName.Where(c => !invalidChars.Contains(c)).ToArray());
  142. }
  143. /// <summary>
  144. /// 文件后缀名签名
  145. /// </summary>
  146. public static Dictionary<string, List<byte[]>> FileSignature => new Dictionary<string, List<byte[]>>
  147. {
  148. { ".jpeg", new List<byte[]>
  149. {
  150. new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 },
  151. new byte[] { 0xFF, 0xD8, 0xFF, 0xE2 },
  152. new byte[] { 0xFF, 0xD8, 0xFF, 0xE3 },
  153. }
  154. },
  155. { ".png", new List<byte[]>
  156. {
  157. new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }
  158. }
  159. },
  160. { ".pdf", new List<byte[]>
  161. {
  162. new byte[] { 0x25, 0x50, 0x44, 0x46 }
  163. }
  164. },
  165. { ".xls", new List<byte[]>
  166. {
  167. new byte[] { 0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1 }
  168. }
  169. },
  170. { ".xlsx", new List<byte[]>
  171. {
  172. new byte[] { 0x50, 0x4B, 0x03, 0x04 }
  173. }
  174. }
  175. };
  176. #endregion
  177. #region IP
  178. /// <summary>
  179. /// 是否为ip
  180. /// </summary>
  181. /// <param name="ip"></param>
  182. /// <returns></returns>
  183. public static bool IsIP(string ip)
  184. {
  185. return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
  186. }
  187. public static string GetIP(HttpRequest request)
  188. {
  189. if (request == null) return "";
  190. var ip = request.Headers["X-Real-IP"].FirstOrDefault();
  191. if (ip.IsNull())
  192. {
  193. ip = request.Headers["X-Forwarded-For"].FirstOrDefault();
  194. }
  195. if (ip.IsNull())
  196. {
  197. ip = request.HttpContext?.Connection?.RemoteIpAddress?.ToString();
  198. }
  199. if (ip.IsNull() || !IsIP(ip))
  200. {
  201. ip = "127.0.0.1";
  202. }
  203. return ip;
  204. }
  205. /// <summary>
  206. /// IP地址获取方法(serilog 单独处理)
  207. /// </summary>
  208. /// <param name="httpContext"></param>
  209. /// <returns></returns>
  210. public static string GetClientIpAddress(HttpContext httpContext)
  211. {
  212. // 1. 尝试从X-Forwarded-For获取(处理代理/负载均衡情况)
  213. if (httpContext.Request.Headers.TryGetValue("X-Forwarded-For", out var forwardedFor))
  214. {
  215. // X-Forwarded-For可能包含逗号分隔的IP列表(客户端,代理1,代理2,...)
  216. var ip = forwardedFor.FirstOrDefault()?.Split(',').FirstOrDefault()?.Trim();
  217. if (!string.IsNullOrEmpty(ip))
  218. return ip;
  219. }
  220. // 2. 尝试从X-Real-IP获取
  221. if (httpContext.Request.Headers.TryGetValue("X-Real-IP", out var realIp))
  222. {
  223. var ip = realIp.FirstOrDefault();
  224. if (!string.IsNullOrEmpty(ip))
  225. return ip;
  226. }
  227. // 3. 使用连接远程IP地址
  228. var remoteIp = httpContext.Connection.RemoteIpAddress;
  229. // 处理IPv6映射的IPv4地址
  230. if (remoteIp != null && remoteIp.IsIPv4MappedToIPv6)
  231. {
  232. remoteIp = remoteIp.MapToIPv4();
  233. }
  234. return remoteIp?.ToString() ?? "unknown";
  235. }
  236. #endregion
  237. #region UserAgent
  238. /// <summary>
  239. /// 分层检测策略实现操作系统识别
  240. /// </summary>
  241. /// <param name="userAgent"></param>
  242. /// <returns></returns>
  243. public static string DetectOS(string userAgent)
  244. {
  245. if (string.IsNullOrEmpty(userAgent)) return "Unknown";
  246. // 移动端优先检测
  247. if (IsMobile(userAgent))
  248. {
  249. if (userAgent.Contains("iPhone")) return ParseIOSVersion(userAgent);
  250. if (userAgent.Contains("Android")) return ParseAndroidVersion(userAgent);
  251. if (userAgent.Contains("Windows Phone")) return "Windows Mobile";
  252. }
  253. // PC端检测
  254. if (userAgent.Contains("Windows NT")) return ParseWindowsVersion(userAgent);
  255. if (userAgent.Contains("Macintosh")) return "macOS";
  256. if (userAgent.Contains("Linux")) return "Linux";
  257. return "Other";
  258. }
  259. /// <summary>
  260. /// 移动设备判断
  261. /// </summary>
  262. /// <param name="userAgent"></param>
  263. /// <returns></returns>
  264. private static bool IsMobile(string userAgent)
  265. {
  266. string[] mobileKeywords = { "iPhone", "Android", "Windows Phone", "iPad", "iPod" };
  267. return mobileKeywords.Any(key => userAgent.Contains(key));
  268. }
  269. /// <summary>
  270. /// iOS版本解析
  271. /// </summary>
  272. /// <param name="userAgent"></param>
  273. /// <returns></returns>
  274. private static string ParseIOSVersion(string userAgent)
  275. {
  276. var match = Regex.Match(userAgent, @"iPhone OS (\d+_\d+)");
  277. return match.Success ? $"iOS {match.Groups[1].Value.Replace('_', '.')}" : "iOS";
  278. }
  279. /// <summary>
  280. /// Android版本解析
  281. /// </summary>
  282. /// <param name="userAgent"></param>
  283. /// <returns></returns>
  284. private static string ParseAndroidVersion(string userAgent)
  285. {
  286. var match = Regex.Match(userAgent, @"Android (\d+)");
  287. return match.Success ? $"Android {match.Groups[1].Value}" : "Android";
  288. }
  289. /// <summary>
  290. /// Windows版本解析
  291. /// </summary>
  292. /// <param name="userAgent"></param>
  293. /// <returns></returns>
  294. private static string ParseWindowsVersion(string userAgent)
  295. {
  296. if (userAgent.Contains("Windows NT 10.0")) return "Windows 10/11";
  297. if (userAgent.Contains("Windows NT 6.3")) return "Windows 8.1";
  298. if (userAgent.Contains("Windows NT 6.2")) return "Windows 8";
  299. return "Windows";
  300. }
  301. #endregion
  302. #region 随机数
  303. /// <summary>
  304. /// 根据自定义随机包含的字符获取指定长度的随机字符
  305. /// </summary>
  306. /// <param name="length">随机字符长度</param>
  307. /// <returns>随机字符</returns>
  308. public static string GetRandomStr(int length)
  309. {
  310. string a = "ABCDEFGHJKLMNPQRSTUVWXYZ012356789";
  311. StringBuilder sb = new StringBuilder();
  312. for (int i = 0; i < length; i++)
  313. {
  314. sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length - 1)]);
  315. }
  316. return sb.ToString();
  317. }
  318. /// <summary>
  319. /// 根据自定义随机包含的字符获取指定长度的随机字符
  320. /// </summary>
  321. /// <param name="length">随机字符长度</param>
  322. /// <returns>随机字符</returns>
  323. public static string GetRandomAllStr(int length)
  324. {
  325. string a = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz012356789";
  326. StringBuilder sb = new StringBuilder();
  327. for (int i = 0; i < length; i++)
  328. {
  329. sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length - 1)]);
  330. }
  331. return sb.ToString();
  332. }
  333. /// <summary>
  334. /// 根据自定义随机包含的字符获取指定长度的随机字母(含大小写)
  335. /// </summary>
  336. /// <param name="length">随机字符长度</param>
  337. /// <returns>随机字符</returns>
  338. public static string GetRandomLetter(int length)
  339. {
  340. string a = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz";
  341. StringBuilder sb = new StringBuilder();
  342. for (int i = 0; i < length; i++)
  343. {
  344. sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length - 1)]);
  345. }
  346. return sb.ToString();
  347. }
  348. /// <summary>
  349. /// 生成不重复随机数字
  350. /// 操作者:037
  351. /// 2021-07-26 15:39
  352. /// </summary>
  353. /// <param name="CodeCount">输入字符串长度</param>
  354. /// <returns>字符串</returns>
  355. public static string GetRandomNumber(int len)
  356. {
  357. string allChar = "0,1,2,3,4,5,6,7,8,9";
  358. string[] allCharArray = allChar.Split(',');
  359. string RandomCode = "";
  360. int temp = -1;
  361. Random rand = new Random();
  362. for (int i = 0; i < len; i++)
  363. {
  364. if (temp != -1)
  365. {
  366. rand = new Random(temp * i * ((int)DateTime.Now.Ticks));
  367. }
  368. int t = rand.Next(allCharArray.Length - 1);
  369. while (temp == t)
  370. {
  371. t = rand.Next(allCharArray.Length - 1);
  372. }
  373. temp = t;
  374. RandomCode += allCharArray[t];
  375. }
  376. return RandomCode;
  377. }
  378. #endregion
  379. #region decimal 截取
  380. /// <summary>
  381. ///
  382. /// </summary>
  383. /// <param name="d"></param>
  384. /// <param name="n"></param>
  385. /// <returns></returns>
  386. public static decimal CutDecimalWithN(decimal d, int n)
  387. {
  388. string strDecimal = d.ToString();
  389. int index = strDecimal.IndexOf(".");
  390. if (index == -1 || strDecimal.Length < index + n + 1)
  391. {
  392. strDecimal = string.Format("{0:F" + n + "}", d);
  393. }
  394. else
  395. {
  396. int length = index;
  397. if (n != 0)
  398. {
  399. length = index + n + 1;
  400. }
  401. strDecimal = strDecimal.Substring(0, length);
  402. }
  403. return Decimal.Parse(strDecimal);
  404. }
  405. /// <summary>
  406. /// decimal 保留小数,不四舍五入
  407. /// </summary>
  408. /// <param name="value"></param>
  409. /// <param name="decimalPlaces"></param>
  410. /// <returns></returns>
  411. public static decimal TruncDecimals(this decimal value, int decimalPlaces)
  412. {
  413. decimal scaleFactor = (decimal)Math.Pow(10, decimalPlaces);
  414. var truncated = Math.Truncate(scaleFactor * value) / scaleFactor;
  415. // 检查是否需要补零
  416. if (GetDecimalDigits(value) < decimalPlaces)
  417. {
  418. string format = "0." + new string('0', decimalPlaces);
  419. truncated = decimal.Parse(truncated.ToString(format));
  420. }
  421. return truncated;
  422. }
  423. private static int GetDecimalDigits(decimal number)
  424. {
  425. string[] parts = number.ToString().Split('.');
  426. return parts.Length > 1 ? parts[1].Length : 0;
  427. }
  428. #endregion
  429. #region decimal 保留两位小数
  430. /// <summary>
  431. /// decimal 保留两位小数 不四舍五入
  432. /// </summary>
  433. /// <param name="number"></param>
  434. /// <returns></returns>
  435. public static decimal DecimalsKeepTwo(this decimal myDecimal)
  436. {
  437. var subDecimal = Math.Floor(myDecimal * 100) / 100;//保留两位小数,直接截取
  438. return subDecimal;
  439. }
  440. #endregion
  441. #region 团组模块 - 汇率相关存储解析
  442. /// <summary>
  443. /// 团组模块 - 汇率相关 To List
  444. /// </summary>
  445. /// <param name="rateStr"></param>
  446. /// <returns></returns>
  447. public static List<CurrencyInfo> GetCurrencyChinaToList(string? rateStr)
  448. {
  449. List<CurrencyInfo> currencyInfos = new List<CurrencyInfo>();
  450. if (string.IsNullOrEmpty(rateStr)) return currencyInfos;
  451. if (rateStr.Contains("|"))
  452. {
  453. string[] currencyArr = rateStr.Split("|");
  454. foreach (string currency in currencyArr)
  455. {
  456. if (!string.IsNullOrEmpty(currency))
  457. {
  458. string[] currency1 = currency.Split(":");
  459. string[] currency2 = currency1[0].Split("(");
  460. CurrencyInfo rateInfo = new CurrencyInfo()
  461. {
  462. CurrencyCode = currency2[1].Replace(")", "").TrimEnd(),
  463. CurrencyName = currency2[0],
  464. Rate = decimal.Parse(currency1[1]),
  465. };
  466. currencyInfos.Add(rateInfo);
  467. }
  468. }
  469. }
  470. return currencyInfos;
  471. }
  472. /// <summary>
  473. /// 团组模块 - 汇率相关存储解析 To String
  474. /// </summary>
  475. /// <param name="rates"></param>
  476. /// <returns></returns>
  477. public static string GetCurrencyChinaToString(List<CurrencyInfo>? rates)
  478. {
  479. string rateStr = string.Empty;
  480. if (rates == null) return rateStr;
  481. if (rates.Count <= 0) return rateStr;
  482. if (rates.Count == 1)
  483. {
  484. var rate = rates[0];
  485. return string.Format("{0}({1}):{2}|", rate.CurrencyName, rate.CurrencyCode, rate.Rate);
  486. }
  487. foreach (CurrencyInfo rate in rates)
  488. {
  489. //存储方式: 美元(USD):6.2350|.......|墨西哥比索(MXN):1.0000
  490. rateStr += string.Format("{0}({1}):{2}|", rate.CurrencyName, rate.CurrencyCode, rate.Rate);
  491. }
  492. if (rateStr.Length > 0)
  493. {
  494. rateStr = rateStr.Substring(0, rateStr.Length - 1);
  495. }
  496. return rateStr;
  497. }
  498. #endregion
  499. #region 验证身份证号码
  500. /// <summary>
  501. /// 正则表达式
  502. /// 验证身份证号码
  503. /// </summary>
  504. /// <param name="idNumber"></param>
  505. /// <returns></returns>
  506. public static bool IsValidChineseId(this string idNumber)
  507. {
  508. string pattern = @"^[1-9]\d{5}(18|19|20|21|22)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$";
  509. Regex regex = new Regex(pattern);
  510. return regex.IsMatch(idNumber);
  511. }
  512. /// <summary>
  513. /// 通过身份证提取生日
  514. /// </summary>
  515. /// <param name="identityCard"></param>
  516. /// <returns></returns>
  517. public static DateTime? GetBirthDateFromIdentityCard(string identityCard)
  518. {
  519. // 身份证号码正则表达式验证,支持18位身份证号码
  520. if (!Regex.IsMatch(identityCard, @"^\d{17}(\d|X|x)$"))
  521. {
  522. return null;
  523. }
  524. // 获取出生日期(8位数字)
  525. string birthDateString = identityCard.Substring(6, 8);
  526. // 尝试将出生日期字符串转换为DateTime类型
  527. if (DateTime.TryParse(birthDateString, out DateTime birthDate))
  528. {
  529. return birthDate;
  530. }
  531. return null;
  532. }
  533. /// <summary>
  534. /// 通过身份证判断性别
  535. /// </summary>
  536. /// <param name="idNumber"></param>
  537. /// <returns>0 男1 女 -1 未设置</returns>
  538. /// <exception cref="ArgumentException"></exception>
  539. public static int GetGenderFromIdentityCard(string idNumber)
  540. {
  541. if (string.IsNullOrEmpty(idNumber) || idNumber.Length != 18)
  542. return -1;
  543. char genderChar = idNumber[16];
  544. return int.Parse(genderChar.ToString()) % 2 == 0 ? 1 : 0;
  545. }
  546. #endregion
  547. #region string格式日期格式化
  548. /// <summary>
  549. /// string格式日期格式化
  550. /// </summary>
  551. /// <param name="dateStr"></param>
  552. /// <param name="format">
  553. /// 格式化标准
  554. /// yyyy-MM-dd yyyy/MM/dd
  555. /// </param>
  556. /// <returns></returns>
  557. public static string DateFormat(this string dateStr, string format)
  558. {
  559. if (!string.IsNullOrEmpty(dateStr))
  560. {
  561. if (!string.IsNullOrEmpty(format))
  562. {
  563. DateTime result;
  564. if (DateTime.TryParse(dateStr, out result))
  565. {
  566. return result.ToString(format);
  567. }
  568. }
  569. }
  570. return "";
  571. }
  572. #endregion
  573. /// <summary>
  574. /// List to DataTable
  575. /// 集合转换成datatable
  576. /// </summary>
  577. /// <typeparam name="T"></typeparam>
  578. /// <param name="aIList"></param>
  579. /// <returns></returns>
  580. public static DataTable GetDataTableFromIList<T>(List<T> aIList)
  581. {
  582. DataTable _returnTable = new DataTable();
  583. if (aIList != null && aIList.Count > 0)
  584. {
  585. object _baseObj = aIList[0];
  586. Type objectType = _baseObj.GetType();
  587. PropertyInfo[] properties = objectType.GetProperties();
  588. DataColumn _col;
  589. foreach (PropertyInfo property in properties)
  590. {
  591. _col = new DataColumn();
  592. _col.ColumnName = (string)property.Name;
  593. _col.DataType = property.PropertyType;
  594. _returnTable.Columns.Add(_col);
  595. }
  596. //Adds the rows to the table
  597. DataRow _row;
  598. foreach (object objItem in aIList)
  599. {
  600. _row = _returnTable.NewRow();
  601. foreach (PropertyInfo property in properties)
  602. {
  603. _row[property.Name] = property.GetValue(objItem, null);
  604. }
  605. _returnTable.Rows.Add(_row);
  606. }
  607. }
  608. return _returnTable;
  609. }
  610. /// <summary>
  611. /// List to DataTable
  612. /// 集合转换成datatable
  613. /// </summary>
  614. public static DataTable ToDataTableArray(IList list)
  615. {
  616. DataTable result = new DataTable();
  617. if (list.Count > 0)
  618. {
  619. PropertyInfo[] propertys = list[0].GetType().GetProperties();
  620. foreach (PropertyInfo pi in propertys)
  621. {
  622. try
  623. {
  624. result.Columns.Add(pi.Name, pi.PropertyType);
  625. }
  626. catch (Exception ex)
  627. {
  628. Console.WriteLine($"{pi.Name}:{ex.Message}");
  629. }
  630. }
  631. for (int i = 0; i < list.Count; i++)
  632. {
  633. ArrayList tempList = new ArrayList();
  634. foreach (PropertyInfo pi in propertys)
  635. {
  636. object obj = pi.GetValue(list[i], null);
  637. tempList.Add(obj);
  638. }
  639. object?[] array = tempList.ToArray();
  640. result.LoadDataRow(array, true);
  641. }
  642. }
  643. return result;
  644. }
  645. /// <summary>
  646. ///获取指定月份起止日期
  647. /// </summary>
  648. /// <param name="year"></param>
  649. /// <param name="month"></param>
  650. /// <returns></returns>
  651. public static (DateTime StartDate, DateTime EndDate) GetMonthStartAndEndDates(int year, int month)
  652. {
  653. var calendar = new GregorianCalendar();
  654. var daysInMonth = calendar.GetDaysInMonth(year, month);
  655. var startDate = new DateTime(year, month, 1);
  656. var endDate = new DateTime(year, month, daysInMonth);
  657. return (startDate, endDate);
  658. }
  659. /// <summary>
  660. /// 验证json字符串是否合法
  661. /// </summary>
  662. /// <param name="jsonString"></param>
  663. /// <returns></returns>
  664. public static bool IsValidJson(string jsonString)
  665. {
  666. try
  667. {
  668. JToken.Parse(jsonString);
  669. return true;
  670. }
  671. catch (JsonReaderException)
  672. {
  673. return false;
  674. }
  675. }
  676. /// <summary>
  677. /// 常见的双字姓氏列表
  678. /// </summary>
  679. private static readonly HashSet<string> commonDoubleSurnames = new HashSet<string>
  680. {
  681. "欧阳", "司马", "上官", "夏侯", "诸葛", "东方", "赫连", "皇甫", "尉迟", "公羊",
  682. "澹台", "公冶", "宗政", "濮阳", "淳于", "单于", "太叔", "申屠", "公孙", "仲孙",
  683. "轩辕", "令狐", "钟离", "宇文", "长孙", "慕容", "鲜于", "闾丘", "司徒", "司空",
  684. "亓官", "司寇", "仉督", "子车", "颛孙", "端木", "巫马", "公西", "漆雕", "乐正",
  685. "壤驷", "公良", "拓跋", "夹谷", "宰父", "谷梁", "晋楚", "闫法", "汝鄢", "涂钦",
  686. "段干", "百里", "东郭", "南门", "呼延", "归海", "羊舌", "微生", "岳帅", "缑亢",
  687. "况后", "有琴", "梁丘", "左丘", "东门", "西门", "商牟", "佘佴", "伯赏", "南宫"
  688. };
  689. /// <summary>
  690. /// 中文名字取姓氏和名字
  691. /// </summary>
  692. /// <param name="fullName"></param>
  693. /// <returns>姓:lastName 名:firstName</returns>
  694. public static (string lastName, string firstName) GetLastNameAndFirstName(string fullName)
  695. {
  696. if (string.IsNullOrEmpty(fullName) || fullName.Length < 2) return ("", "");
  697. // 尝试匹配双字姓氏
  698. if (fullName.Length > 2)
  699. {
  700. string potentialDoubleSurname = fullName.Substring(0, 2);
  701. if (commonDoubleSurnames.Contains(potentialDoubleSurname))
  702. {
  703. string lastName = potentialDoubleSurname;
  704. string firstName = fullName.Substring(2);
  705. return (lastName, firstName);
  706. }
  707. }
  708. // 默认单字姓氏
  709. string singleSurname = fullName.Substring(0, 1);
  710. string remainingName = fullName.Substring(1);
  711. return (singleSurname, remainingName);
  712. }
  713. /// <summary>
  714. /// 中文名字转拼音
  715. /// </summary>
  716. /// <param name="chineseName"></param>
  717. /// <returns></returns>
  718. /// <exception cref="ArgumentException"></exception>
  719. public static string ConvertToPinyin(string chineseName)
  720. {
  721. if (string.IsNullOrEmpty(chineseName)) return "";
  722. return PinyinHelper.GetPinyin(chineseName, "").ToUpper();
  723. }
  724. #region stringBuilder 扩展
  725. /// <summary>
  726. /// StringBuilder 验证是否有值
  727. /// </summary>
  728. /// <param name="sb"></param>
  729. /// <returns></returns>
  730. public static bool HasValue(this StringBuilder sb)
  731. {
  732. return sb != null && sb.Length > 0;
  733. }
  734. #endregion
  735. }