CommonFun.cs 26 KB

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