CommonFun.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  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. string[] currency1 = currency.Split(":");
  457. string[] currency2 = currency1[0].Split("(");
  458. CurrencyInfo rateInfo = new CurrencyInfo()
  459. {
  460. CurrencyCode = currency2[1].Replace(")", "").TrimEnd(),
  461. CurrencyName = currency2[0],
  462. Rate = decimal.Parse(currency1[1]),
  463. };
  464. currencyInfos.Add(rateInfo);
  465. }
  466. }
  467. return currencyInfos;
  468. }
  469. /// <summary>
  470. /// 团组模块 - 汇率相关存储解析 To String
  471. /// </summary>
  472. /// <param name="rates"></param>
  473. /// <returns></returns>
  474. public static string GetCurrencyChinaToString(List<CurrencyInfo>? rates)
  475. {
  476. string rateStr = string.Empty;
  477. if (rates == null) return rateStr;
  478. if (rates.Count <= 0) return rateStr;
  479. if (rates.Count == 1)
  480. {
  481. var rate = rates[0];
  482. return string.Format("{0}({1}):{2}|", rate.CurrencyName, rate.CurrencyCode, rate.Rate);
  483. }
  484. foreach (CurrencyInfo rate in rates)
  485. {
  486. //存储方式: 美元(USD):6.2350|.......|墨西哥比索(MXN):1.0000
  487. rateStr += string.Format("{0}({1}):{2}|", rate.CurrencyName, rate.CurrencyCode, rate.Rate);
  488. }
  489. if (rateStr.Length > 0)
  490. {
  491. rateStr = rateStr.Substring(0, rateStr.Length - 1);
  492. }
  493. return rateStr;
  494. }
  495. #endregion
  496. #region 验证身份证号码
  497. /// <summary>
  498. /// 正则表达式
  499. /// 验证身份证号码
  500. /// </summary>
  501. /// <param name="idNumber"></param>
  502. /// <returns></returns>
  503. public static bool IsValidChineseId(this string idNumber)
  504. {
  505. 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])$";
  506. Regex regex = new Regex(pattern);
  507. return regex.IsMatch(idNumber);
  508. }
  509. /// <summary>
  510. /// 通过身份证提取生日
  511. /// </summary>
  512. /// <param name="identityCard"></param>
  513. /// <returns></returns>
  514. public static DateTime? GetBirthDateFromIdentityCard(string identityCard)
  515. {
  516. // 身份证号码正则表达式验证,支持18位身份证号码
  517. if (!Regex.IsMatch(identityCard, @"^\d{17}(\d|X|x)$"))
  518. {
  519. return null;
  520. }
  521. // 获取出生日期(8位数字)
  522. string birthDateString = identityCard.Substring(6, 8);
  523. // 尝试将出生日期字符串转换为DateTime类型
  524. if (DateTime.TryParse(birthDateString, out DateTime birthDate))
  525. {
  526. return birthDate;
  527. }
  528. return null;
  529. }
  530. /// <summary>
  531. /// 通过身份证判断性别
  532. /// </summary>
  533. /// <param name="idNumber"></param>
  534. /// <returns>0 男1 女 -1 未设置</returns>
  535. /// <exception cref="ArgumentException"></exception>
  536. public static int GetGenderFromIdentityCard(string idNumber)
  537. {
  538. if (string.IsNullOrEmpty(idNumber) || idNumber.Length != 18)
  539. return -1;
  540. char genderChar = idNumber[16];
  541. return int.Parse(genderChar.ToString()) % 2 == 0 ? 1 : 0;
  542. }
  543. #endregion
  544. #region string格式日期格式化
  545. /// <summary>
  546. /// string格式日期格式化
  547. /// </summary>
  548. /// <param name="dateStr"></param>
  549. /// <param name="format">
  550. /// 格式化标准
  551. /// yyyy-MM-dd yyyy/MM/dd
  552. /// </param>
  553. /// <returns></returns>
  554. public static string DateFormat(this string dateStr, string format)
  555. {
  556. if (!string.IsNullOrEmpty(dateStr))
  557. {
  558. if (!string.IsNullOrEmpty(format))
  559. {
  560. DateTime result;
  561. if (DateTime.TryParse(dateStr, out result))
  562. {
  563. return result.ToString(format);
  564. }
  565. }
  566. }
  567. return "";
  568. }
  569. #endregion
  570. /// <summary>
  571. /// List to DataTable
  572. /// 集合转换成datatable
  573. /// </summary>
  574. /// <typeparam name="T"></typeparam>
  575. /// <param name="aIList"></param>
  576. /// <returns></returns>
  577. public static DataTable GetDataTableFromIList<T>(List<T> aIList)
  578. {
  579. DataTable _returnTable = new DataTable();
  580. if (aIList != null && aIList.Count > 0)
  581. {
  582. object _baseObj = aIList[0];
  583. Type objectType = _baseObj.GetType();
  584. PropertyInfo[] properties = objectType.GetProperties();
  585. DataColumn _col;
  586. foreach (PropertyInfo property in properties)
  587. {
  588. _col = new DataColumn();
  589. _col.ColumnName = (string)property.Name;
  590. _col.DataType = property.PropertyType;
  591. _returnTable.Columns.Add(_col);
  592. }
  593. //Adds the rows to the table
  594. DataRow _row;
  595. foreach (object objItem in aIList)
  596. {
  597. _row = _returnTable.NewRow();
  598. foreach (PropertyInfo property in properties)
  599. {
  600. _row[property.Name] = property.GetValue(objItem, null);
  601. }
  602. _returnTable.Rows.Add(_row);
  603. }
  604. }
  605. return _returnTable;
  606. }
  607. /// <summary>
  608. /// List to DataTable
  609. /// 集合转换成datatable
  610. /// </summary>
  611. public static DataTable ToDataTableArray(IList list)
  612. {
  613. DataTable result = new DataTable();
  614. if (list.Count > 0)
  615. {
  616. PropertyInfo[] propertys = list[0].GetType().GetProperties();
  617. foreach (PropertyInfo pi in propertys)
  618. {
  619. try
  620. {
  621. result.Columns.Add(pi.Name, pi.PropertyType);
  622. }
  623. catch (Exception ex)
  624. {
  625. Console.WriteLine($"{pi.Name}:{ex.Message}");
  626. }
  627. }
  628. for (int i = 0; i < list.Count; i++)
  629. {
  630. ArrayList tempList = new ArrayList();
  631. foreach (PropertyInfo pi in propertys)
  632. {
  633. object obj = pi.GetValue(list[i], null);
  634. tempList.Add(obj);
  635. }
  636. object?[] array = tempList.ToArray();
  637. result.LoadDataRow(array, true);
  638. }
  639. }
  640. return result;
  641. }
  642. /// <summary>
  643. ///获取指定月份起止日期
  644. /// </summary>
  645. /// <param name="year"></param>
  646. /// <param name="month"></param>
  647. /// <returns></returns>
  648. public static (DateTime StartDate, DateTime EndDate) GetMonthStartAndEndDates(int year, int month)
  649. {
  650. var calendar = new GregorianCalendar();
  651. var daysInMonth = calendar.GetDaysInMonth(year, month);
  652. var startDate = new DateTime(year, month, 1);
  653. var endDate = new DateTime(year, month, daysInMonth);
  654. return (startDate, endDate);
  655. }
  656. /// <summary>
  657. /// 验证json字符串是否合法
  658. /// </summary>
  659. /// <param name="jsonString"></param>
  660. /// <returns></returns>
  661. public static bool IsValidJson(string jsonString)
  662. {
  663. try
  664. {
  665. JToken.Parse(jsonString);
  666. return true;
  667. }
  668. catch (JsonReaderException)
  669. {
  670. return false;
  671. }
  672. }
  673. /// <summary>
  674. /// 常见的双字姓氏列表
  675. /// </summary>
  676. private static readonly HashSet<string> commonDoubleSurnames = new HashSet<string>
  677. {
  678. "欧阳", "司马", "上官", "夏侯", "诸葛", "东方", "赫连", "皇甫", "尉迟", "公羊",
  679. "澹台", "公冶", "宗政", "濮阳", "淳于", "单于", "太叔", "申屠", "公孙", "仲孙",
  680. "轩辕", "令狐", "钟离", "宇文", "长孙", "慕容", "鲜于", "闾丘", "司徒", "司空",
  681. "亓官", "司寇", "仉督", "子车", "颛孙", "端木", "巫马", "公西", "漆雕", "乐正",
  682. "壤驷", "公良", "拓跋", "夹谷", "宰父", "谷梁", "晋楚", "闫法", "汝鄢", "涂钦",
  683. "段干", "百里", "东郭", "南门", "呼延", "归海", "羊舌", "微生", "岳帅", "缑亢",
  684. "况后", "有琴", "梁丘", "左丘", "东门", "西门", "商牟", "佘佴", "伯赏", "南宫"
  685. };
  686. /// <summary>
  687. /// 中文名字取姓氏和名字
  688. /// </summary>
  689. /// <param name="fullName"></param>
  690. /// <returns>姓:lastName 名:firstName</returns>
  691. public static (string lastName, string firstName) GetLastNameAndFirstName(string fullName)
  692. {
  693. if (string.IsNullOrEmpty(fullName) || fullName.Length < 2) return ("", "");
  694. // 尝试匹配双字姓氏
  695. if (fullName.Length > 2)
  696. {
  697. string potentialDoubleSurname = fullName.Substring(0, 2);
  698. if (commonDoubleSurnames.Contains(potentialDoubleSurname))
  699. {
  700. string lastName = potentialDoubleSurname;
  701. string firstName = fullName.Substring(2);
  702. return (lastName, firstName);
  703. }
  704. }
  705. // 默认单字姓氏
  706. string singleSurname = fullName.Substring(0, 1);
  707. string remainingName = fullName.Substring(1);
  708. return (singleSurname, remainingName);
  709. }
  710. /// <summary>
  711. /// 中文名字转拼音
  712. /// </summary>
  713. /// <param name="chineseName"></param>
  714. /// <returns></returns>
  715. /// <exception cref="ArgumentException"></exception>
  716. public static string ConvertToPinyin(string chineseName)
  717. {
  718. if (string.IsNullOrEmpty(chineseName)) return "";
  719. return PinyinHelper.GetPinyin(chineseName, "").ToUpper();
  720. }
  721. #region stringBuilder 扩展
  722. /// <summary>
  723. /// StringBuilder 验证是否有值
  724. /// </summary>
  725. /// <param name="sb"></param>
  726. /// <returns></returns>
  727. public static bool HasValue(this StringBuilder sb)
  728. {
  729. return sb != null && sb.Length > 0;
  730. }
  731. #endregion
  732. }