C#高級:常用的擴展方法大全

1.String

public static class StringExtensions
{/// <summary>/// 字符串轉List(中逗 英逗分隔)/// </summary>public static List<string> SplitCommaToList(this string data){if (string.IsNullOrEmpty(data)){return new List<string>();}data = data.Replace(",", ",");//中文逗號轉化為英文return data.Split(",").ToList();}/// <summary>/// 字典按序替換字符串(用key代替value)/// </summary>/// <returns></returns>public static string DictionaryReplace(this string input, Dictionary<string, string> replacements){if (string.IsNullOrEmpty(input) || replacements == null || replacements.Count == 0){return input;}foreach (var replacement in replacements){input = input.Replace(replacement.Value, replacement.Key);//用key代替value}return input;}/// <summary>/// 反序列化成實體/// </summary>public static T ConvertToEntity<T>(this string json)//可傳入列表,實體{return JsonSerializer.Deserialize<T>(json);}}

2.DateTime

3.List

public static class ListExtensions
{/// <summary>/// 例如輸入1 3 輸出第1個(含)到第3個(含)的實體列表/// </summary>public static List<T> GetRangeList<T>(this List<T> list, int startIndex, int endIndex){// 檢查索引范圍是否有效if (startIndex < 1 || endIndex > list.Count || startIndex > endIndex){//throw new ArgumentOutOfRangeException("輸入的索引值超出了列表的長度或范圍不正確!");return new List<T>();}// 返回指定范圍內的元素return list.GetRange(startIndex - 1, endIndex - startIndex + 1);}/// <summary>/// 傳入列表和需要獲取的數量,返回隨機選出的元素/// </summary>/// <returns></returns>public static List<T> GetRandomList<T>(this List<T> list, int count){// 檢查列表是否足夠if (list.Count < count){//throw new ArgumentException("列表中的元素不足,無法隨機選擇所需數量的元素。");return new List<T>();}// 使用 Random 類生成隨機索引Random random = new Random();// 隨機選擇不重復的元素return list.OrderBy(x => random.Next()).Take(count).ToList();}/// <summary>/// 按指定字段,順序排序,且返回xx條/// </summary>/// <returns></returns>public static List<V> OrderByAndTake<T, V>(this List<V> list, Expression<Func<V, T>> keySelector, int count){if (list == null || !list.Any() || count <= 0){return new List<V>();}var sortedlist = list.OrderBy(keySelector.Compile());return sortedlist.Take(count).ToList();}/// <summary>/// 按指定字段,倒序排序,且返回xx條/// </summary>/// <returns></returns>public static List<V> OrderByDescAndTake<T, V>(this List<V> list, Expression<Func<V, T>> keySelector, int count){if (list == null || !list.Any() || count <= 0){return new List<V>();}var sortedlist = list.OrderByDescending(keySelector.Compile());return sortedlist.Take(count).ToList();}/// <summary>/// 傳入列表,返回一個元組(索引,列表實體)/// </summary>/// <returns></returns>public static List<(int index , T entity)> GetIndexList<T>(this List<T> list){List<(int index, T entity)> result = new List<(int index, T entity)>();for (int i = 0; i < list.Count; i++){result.Add((i, list[i]));}return result;}/// <summary>/// 列表為null或空列表則返回True/// </summary>/// <returns></returns>public static bool IsNullOrEmpty<T>(this List<T> list){return list == null || !list.Any();}/// <summary>/// 一個實體列表映射到另一個實體列表(屬性名稱相同則映射)/// </summary>public static List<TTarget> MapToList<TTarget>(this IEnumerable<object> sourceList) where TTarget : new(){var targetList = new List<TTarget>();foreach (var source in sourceList){var target = new TTarget();var sourceProperties = source.GetType().GetProperties(); // 使用實際對象的類型var targetProperties = typeof(TTarget).GetProperties();foreach (var sourceProp in sourceProperties){var targetProp = targetProperties.FirstOrDefault(tp => tp.Name == sourceProp.Name && tp.CanWrite);if (targetProp != null && targetProp.PropertyType == sourceProp.PropertyType){targetProp.SetValue(target, sourceProp.GetValue(source));}}targetList.Add(target);}return targetList;}/// <summary>/// 列表轉JSON(string)/// </summary>/// <returns></returns>public static string ConvertToJson<T>(this List<T> sourceList)//可傳入列表,實體{var options = new JsonSerializerOptions{Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping // 禁用 Unicode 轉義,防止中文字符轉義為 Unicode};return JsonSerializer.Serialize(sourceList, options);}}

4.Entity

public static class EntityExtensions
{/// <summary>/// 實體轉JSON/// </summary>public static string ConvertToJson<T>(T entity)//可傳入列表,實體{var options = new JsonSerializerOptions{Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping // 禁用 Unicode 轉義,防止中文字符轉義為 Unicode};return JsonSerializer.Serialize(entity, options);}/// <summary>/// 將一個實體映射到另一個實體(屬性名稱相同且類型匹配的屬性將映射)/// </summary>public static TTarget MapToEntity<TTarget>(this object source) where TTarget : new(){var target = new TTarget();var sourceProperties = source.GetType().GetProperties(); // 獲取源實體的屬性var targetProperties = typeof(TTarget).GetProperties(); // 獲取目標實體的屬性foreach (var sourceProp in sourceProperties){var targetProp = targetProperties.FirstOrDefault(tp => tp.Name == sourceProp.Name && tp.CanWrite);if (targetProp != null && targetProp.PropertyType == sourceProp.PropertyType){targetProp.SetValue(target, sourceProp.GetValue(source));}}return target;}/// <summary>/// 通過反射設置實體的值/// </summary>/// <typeparam name="T"></typeparam>/// <returns></returns>public static void SetValueByReflect<T>(this T entity, string feildName, object feildValue) where T : class{var feild = typeof(T).GetProperty(feildName);var feildType = feild?.PropertyType;if (feild != null && feildType != null){var valueToSet = Convert.ChangeType(feildValue, feildType);//輸入的值類型轉化為實體屬性的類型feild.SetValue(entity, valueToSet);}}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/67039.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/67039.shtml
英文地址,請注明出處:http://en.pswp.cn/web/67039.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【Numpy核心編程攻略:Python數據處理、分析詳解與科學計算】1.1 從零搭建NumPy環境:安裝指南與初體驗

1. 從零搭建NumPy環境&#xff1a;安裝指南與初體驗 NumPy核心能力圖解&#xff08;架構圖&#xff09; NumPy 是 Python 中用于科學計算的核心庫&#xff0c;它提供了高效的多維數組對象以及用于處理這些數組的各種操作。NumPy 的核心能力可以概括為以下幾個方面&#xff1a…

【SpringBoot教程】Spring Boot + MySQL + HikariCP 連接池整合教程

&#x1f64b;大家好&#xff01;我是毛毛張! &#x1f308;個人首頁&#xff1a; 神馬都會億點點的毛毛張 在前面一篇文章中毛毛張介紹了SpringBoot中數據源與數據庫連接池相關概念&#xff0c;今天毛毛張要分享的是關于SpringBoot整合HicariCP連接池相關知識點以及底層源碼…

Java進階(一)

目錄 一.Java注解 什么是注解&#xff1f; 內置注解 元注解 二.對象克隆 什么是對象克隆? 為什么用到對象克隆 三.淺克隆深克隆 一.Java注解 什么是注解&#xff1f; java中注解(Annotation)又稱java標注&#xff0c;是一種特殊的注釋。 可以添加在包&#xff0c;類&…

【PyCharm】將包含多個參數的 shell 腳本配置到執行文件來調試 Python 程序

要配置 PyCharm 以使用包含多個參數的 shell 腳本&#xff08;如 run.sh&#xff09;來調試 Python 程序&#xff0c;您可以按照以下步驟操作&#xff1a; 創建一個新的運行/調試配置&#xff1a; 在 PyCharm 中&#xff0c;點擊“運行”菜單旁邊的齒輪圖標&#xff0c;選擇“…

即夢(Dreamina)技術淺析(二):后端AI服務

1. 文本處理(Text Processing) 1.1 功能概述 文本處理模塊的主要任務是將用戶輸入的文字提示詞轉換為機器可以理解的向量表示。這一過程包括分詞、詞嵌入和語義編碼,旨在捕捉文本的語義信息,為后續的圖像和視頻生成提供準確的指導。 1.2 關鍵技術 1.分詞(Tokenization…

藍橋杯之c++入門(一)【第一個c++程序】

目錄 前言一、第?個C程序1.1 基礎程序1.2 main函數1.3 字符串1.4 頭文件1.5 cin 和 cout 初識1.6 名字空間1.7 注釋 二、四道簡單習題&#xff08;點擊跳轉鏈接&#xff09;練習1&#xff1a;Hello,World!練習2&#xff1a;打印飛機練習3&#xff1a;第?個整數練習4&#xff…

【C++初階】第11課—vector

文章目錄 1. 認識vector2. vector的遍歷3. vector的構造4. vector常用的接口5. vector的容量6. vector的元素訪問7. vector的修改8. vector<vector\<int\>>的使用9. vector的使用10. 模擬實現vector11. 迭代器失效11.1 insert插入數據內部迭代器失效11.2 insert插入…

【AIGC學習筆記】扣子平臺——精選有趣應用,探索無限可能

背景介紹&#xff1a; 由于近期業務發展的需求&#xff0c;我開始接觸并深入了解了扣子平臺的相關知識&#xff0c;并且通過官方教程自學了簡易PE工作流搭建的技巧。恰逢周會需要準備與工作相關的分享主題&#xff0c;而我作為一個扣子平臺的初學者&#xff0c;也想探索一下這…

mysql 學習6 DML語句,對數據庫中的表進行 增 刪 改 操作

添加數據 我們對 testdatabase 數據中 的 qqemp 這張表進行 增加數據&#xff0c;在這張表 下 打開 命令行 query console 在 軟件中就是打開命令行的意思 可以先執行 desc qqemp; 查看一下當前表的結構。 插入一條數據 到qqemp 表&#xff0c;插入時要每個字段都有值 insert…

Java Web-Request與Response

在 Java Web 開發中&#xff0c;Request 和 Response 是兩個非常重要的對象&#xff0c;用于在客戶端和服務器之間進行請求和響應的處理&#xff0c;以下是詳細介紹&#xff1a; Request&#xff08;請求對象&#xff09; Request繼承體系 在 Java Web 開發中&#xff0c;通…

李沐vscode配置+github管理+FFmpeg視頻搬運+百度API添加翻譯字幕

終端輸入nvidia-smi查看cuda版本 我的是12.5&#xff0c;在網上沒有找到12.5的torch&#xff0c;就安裝12.1的。torch&#xff0c;torchvision&#xff0c;torchaudio版本以及python版本要對應 參考&#xff1a;https://blog.csdn.net/FengHanI/article/details/135116114 創…

論文閱讀(十六):利用線性鏈條件隨機場模型檢測陣列比較基因組雜交數據的拷貝數變異

1.論文鏈接&#xff1a;Detection of Copy Number Variations from Array Comparative Genomic Hybridization Data Using Linear-chain Conditional Random Field Models 摘要&#xff1a; 拷貝數變異&#xff08;CNV&#xff09;約占人類基因組的12%。除了CNVs在癌癥發展中的…

Alibaba Spring Cloud 十三 Nacos,Gateway,Nginx 部署架構與負載均衡方案

在微服務體系中&#xff0c;Nacos 主要承擔“服務注冊與發現、配置中心”的職能&#xff0c;Gateway&#xff08;如 Spring Cloud Gateway&#xff09;通常負責“路由轉發、過濾、安全鑒權、灰度流量控制”等功能&#xff0c;而 Nginx 則常被用作“邊緣反向代理”或“統一流量入…

Next.js 實戰 (十):中間件的魅力,打造更快更安全的應用

什么是中間件&#xff1f; 在 Next.js 中&#xff0c;中間件&#xff08;Middleware&#xff09;是一種用于處理每個傳入請求的功能。它允許你在請求到達頁面之前對其進行修改或響應。 通過中間件&#xff0c;你可以實現諸如日志記錄、身份驗證、重定向、CORS配置、壓縮等任務…

ElasticSearch-文檔元數據樂觀并發控制

文章目錄 什么是文檔&#xff1f;文檔元數據文檔的部分更新Update 樂觀并發控制 最近日常工作開發過程中使用到了 ES&#xff0c;最近在檢索資料的時候翻閱到了 ES 的官方文檔&#xff0c;里面對 ES 的基礎與案例進行了通俗易懂的解釋&#xff0c;讀下來也有不少收獲&#xff0…

實驗二 數據庫的附加/分離、導入/導出與備份/還原

實驗二 數據庫的附加/分離、導入/導出與備份/還原 一、實驗目的 1、理解備份的基本概念&#xff0c;掌握各種備份數據庫的方法。 2、掌握如何從備份中還原數據庫。 3、掌握數據庫中各種數據的導入/導出。 4、掌握數據庫的附加與分離&#xff0c;理解數據庫的附加與分離的作用。…

技術中臺與終搜——2

文章目錄 5、語言處理與自動補全技術探測5.1 自定義語料庫5.1.1 語料庫映射OpenAPI5.1.2 語料庫文檔OpenAPI 5.2 產品搜索與自動補全5.2.1 漢字補全OpenAPI5.2.2 拼音補全OpenAPI 5.3 產品搜索與語言處理5.3.1 什么是語言處理&#xff08;拼寫糾錯&#xff09;5.3.2 語言處理Op…

15_業務系統基類

創建腳本 SystemRoot.cs 因為 業務系統基類的子類 會涉及資源加載服務層ResSvc.cs 和 音樂播放服務層AudioSvc.cs 所以在業務系統基類 提取引用資源加載服務層ResSvc.cs 和 音樂播放服務層AudioSvc.cs 并調用單例初始化 using UnityEngine; // 功能 : 業務系統基類 public c…

k8s優雅重啟

理論上處于terminating狀態的pod&#xff0c;k8s 就會把它從service中移除了&#xff0c;只用配置一個優雅停機時長就行了。kubectl get endpoints 驗證 因此&#xff0c;優雅重新的核心問題&#xff0c;是怎么讓空閑長連接關閉&#xff0c;再等待處理中的請求執行完。 一些底…

【Linux】華為服務器使用U盤安裝統信操作系統

目錄 一、準備工作 1.1 下載UOS官方系統 &#xff11;.&#xff12;制作啟動U盤 1.3 服務器智能管理系統iBMC 二、iBMC設置U盤啟動 一、準備工作 1.1 下載UOS官方系統 服務器CPU的架構是x86-64還是aarch64&#xff09;,地址&#xff1a;統信UOS生態社區 - 打造操作系統創…