發表文章

目前顯示的是有「C#」標籤的文章

C# Func用法

C# Func用法 在 C# 中, Func 是一個委託類型,用於表示具有返回值的方法。 Func 委託可以有零個或多個輸入參數,但必須有一個返回值。這使得 Func 非常適合用來封裝那些需要計算並返回結果的方法。 基本語法 Func 委託的定義如下: Func<in T1, in T2, ..., out TResult> T1, T2, ... 是輸入參數的類型。 TResult 是返回值的類型。 示例 以下是一些 Func 的常見用法示例: 1.沒有參數,返回一個值 Func<int> getRandomNumber = () => new Random().Next(1, 100); int number = getRandomNumber(); Console.WriteLine(number); 這個例子中, getRandomNumber 是一個沒有輸入參數但返回一個隨機數的 Func<int> 委託。 2.一個參數,返回一個值 Func<int, int> square = x => x * x; int result = square(5); Console.WriteLine(result); // Output: 25 3.多個參數,返回一個值 Func<int, int, int> add = (a, b) => a + b; int sum = add(3, 4); Console.WriteLine(sum); // Output: 7 在這個例子中, add 是一個接受兩個整數並返回它們和的 Func<int, int, int> 。 Func 的優點 簡潔 :使用 Func 可以減少冗長的代碼,特別是在使用匿名方法或 Lambda 表達式時。 靈活 :可以將方法作為參數傳遞給其他方法,這在 LINQ 查詢中非常常見。 與 Action 的比較 Func 與 Action 類似,但 Action 沒有返回值。 Func 總是有返回值,因此如果你需要一個不返回值的委託,應該使用 Action 。 綜合應用 例如,在 LINQ 查詢中,你經常會看到 Func 被用來...

C# 時間函數 DateTime.Compare(datetime1, datetime2)用法

C# 時間函數 DateTime.Compare(datetime1, datetime2)用法 using System; class Program { static void Main() { DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0); // 8月1日午夜 DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0); // 同一天的中午 int result = DateTime.Compare(date1, date2); string relationship; if (result < 0) relationship = "is earlier than"; //date1 < date2 else if (result == 0) relationship = "is the same time as"; //date1 == date2 else relationship = "is later than"; //date1 > date2 Console.WriteLine("{0} {1} {2}", date1, relationship, date2); } }  

C# 建立物件的淺層複製(Shallow Clone/Copy)及深層複製(Deep Clone/Copy)

C# 建立物件的淺層複製(Shallow Clone/Copy)及深層複製(Deep Clone/Copy) 在C#中,物件的淺層複製(Shallow Copy)和深層複製(Deep Copy)是兩種不同的複製方式,它們在複製物件時的行為和結果有所不同。 淺層複製(Shallow Copy) 淺層複製是指創建一個新的物件,並將原物件的值類型字段複製到新物件中。然而,當數據是參考類型時,只有參考本身被複製,而不是被參考的物件本身。因此,原物件和複製物件將指向同一個物件。這意味著,如果修改了複製物件中的參考類型字段,原物件中的相同字段也會被修改。 在C#中,可以使用 MemberwiseClone() 方法來實現淺層複製。這個方法會創建一個新的物件,並將原物件的所有字段複製到新物件中。但是,如果字段是參考類型,則只複製參考,而不是參考的物件本身。 public object Shallowcopy() { return this.MemberwiseClone(); } 深層複製(Deep Copy) 深層複製則是創建一個新的物件,並將原物件的所有字段(包括參考類型字段)複製到新物件中。這意味著,即使是參考類型字段,也會創建一個新的物件來替換原物件中的參考。因此,原物件和複製物件之間的參考類型字段是完全獨立的,修改其中一個不會影響另一個。 在C#中,實現深層複製需要手動實現。這通常涉及到創建一個新的物件,並將原物件的所有字段(包括參考類型字段)複製到新物件中,並確保參考類型字段也被複製。 深層複製的寫法有很多種, 方法1: 二進制序列化(Binary Serialization) 複製對象 Class 必需標記 [Serializable] 標籤 [Serializable] public class Person { public string Name { get; set; } public int Age { get; set; } } public static T DeepClone<T>(this T source) { if (!typeof(T).IsSerializable) { throw new ArgumentException(...

C# Entityframework, mssql, decimal精準度問題

C# Entityframework, mssql, decimal精準度問題 This is because Entity Framework, by default, maps the .NET decimal type to SQL Server's decimal(18,2) data type, which might not match the precision and scale you require for your specific use case. 由於Entity Framework, .Net decimal型別, 預計對應MSSQL decimal型別的精準度為decimal(18, 2), 所以當C#寫入資料包含小數第3位時, 寫入資料庫後會被截掉。 解決方案如下, 使用Fluent API:如果您使用的是Entity Framework 6,您可以在OnModelCreating方法中使用Fluent API來設定資料庫欄位的精確度和小數位數 protected override void OnModelCreating(DbModelBuilder modelBuilder) { //指定所有decimal欄位轉換 modelBuilder.Properties<decimal>().Configure(config => config.HasPrecision(18, 5)); //指定特定欄位轉換 modelBuilder.Entity<YourEntity>().Property(e => e.YourDecimalProperty).HasPrecision(18, 5); } 若為 Entity Framework Core, 也可使用下面2個寫法 (未實際驗證過是否可行) public Class YourEntity { [Column(TypeName = "decimal(18,5)")] public decimal YourDecimalProperty {get; set;} } protected override void OnModelCreating(ModelBuil...

C# 使用Get取得網頁執行結果資料(資料格式為JSON) [HttpWebRequest]

C# 使用Get取得網頁執行結果資料(資料格式為JSON) [HttpWebRequest] void Main() { string apiUrl = "http://aaa/bbb/ccc?x=11&y=222"; string Msg = ""; HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(apiUrl); req.Method = "GET"; req.ContentType = "application/json"; req.Timeout = 3000000; //以毫秒為單位 using (HttpWebResponse wr = (HttpWebResponse)req.GetResponse()) { if (wr.StatusCode == HttpStatusCode.OK) { using (Stream stream = wr.GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) { Msg = reader.ReadToEnd(); } } } RDataSS RData = JsonConvert.DeserializeObject<RDataSS>(Msg); RData.Dump(); } // Define other methods and classes here public class RDataSS { public string ReturnCode { get; set; } public string Message { get; set; } public string StorageID { get; set; } }  

C# 使用Get取得網頁執行結果資料(資料格式為JSON) [HttpClient ]

C# 使用Get取得網頁執行結果資料(資料格式為JSON) [HttpClient]  void Main() { string apiUrl = "http://aaa/bbb/ccc?x=11&y=222"; using (HttpClient client = new HttpClient()) { // 執行GET請求並取得回應 HttpResponseMessage response = client.GetAsync(apiUrl).Result; // 確認回應是否成功 response.EnsureSuccessStatusCode(); // 讀取回應內容並解析成字串 string responseBody = response.Content.ReadAsStringAsync().Result; responseBody.Dump(); // 將JSON字串轉換成物件,假設回傳的JSON結構是一個物件的話 // 如果是陣列或其他結構,請使用相對應的方法進行解析 // 你需要使用Json.NET或System.Text.Json等套件進行解析 // 這裡以Json.NET為例 RDataSS responseObject = Newtonsoft.Json.JsonConvert.DeserializeObject<RDataSS>(responseBody); responseObject.Dump(); } } // Define other methods and classes here public class RDataSS { public string ReturnCode { get; set; } public string Message { get; set; } public string AAAA { get; set; } }  

C# 變數, 兩種宣告類型

C# 變數, 兩種宣告類型 基本資料型別(Primitive data types) int, decimal 宣告方式為 int a = 0; DateTime是一個Struct, 所以屬於基本資料型別 宣告方式為DateTime dt = DateTime.Now; 參考型別(Reference types) object, File 宣告方式為 object o = new object 宣告要使用new, 來實體化後, 再放入左方變更, 若沒new, 變數初始值為null    

C#, LINQ, 利用group new 來取得多欄位group by

C#, LINQ, 利用group new 來取得多欄位group by void Main() { // 建立 ClassA 的 List List<ClassA> classAList = new List<ClassA> { new ClassA("A1", 10), new ClassA("A2", 20), new ClassA("A3", 30), new ClassA("A1", 15), new ClassA("A2", 25), new ClassA("A3", 35) }; // 建立 ClassB 的 List List<ClassB> classBList = new List<ClassB> { new ClassB("A1", "C1"), new ClassB("A2", "C2") }; //classAList.Dump(); //classBList.Dump(); // 使用 LINQ 進行關聯和分組 var query = from a in classAList join b in classBList on a.A equals b.A select a; query.Dump(); var query2 = from a in query group new { a.A, a.B } by a.A into grouped select new { A = grouped.Key, SumB = grouped.Sum(item => item.B) }; query2.Dump(); } // Define other methods and classes here // ClassA 定義 class ClassA { public string A { g...

使用EntityFramework批次刪除資料

使用EntityFramework批次刪除資料 using (EntitiesContext db = new EntitiesContext(connString)) { // Retrieve all records from database for deletion IEnumerable<entity> entityList = db.entity.where(x => x.id == id).toList(); // Use Remove Range function to delete all records at once db.entity.RemoveRange(entityList); // Save changes db.SaveChanges(); }  

LINQ, 依筆數切分Datatable為多個Datatable

LINQ, 依筆數切分Datatable為多個Datatable using System; using System.Data; using System.Linq; class Program { static void Main() { // 假設有一個包含資料的 DataTable DataTable originalDataTable = GetOriginalDataTable(); // 指定每個小 DataTable 的大小 int batchSize = 1000; // 使用 LINQ 拆解 DataTable var smallDataTables = originalDataTable.AsEnumerable() .Select((row, index) => new { row, index }) .GroupBy(x => x.index / batchSize) .Select(group => group.Select(x => x.row) .CopyToDataTable()) .ToList(); // 打印結果,這裡只是簡單的範例,實際上你可能需要對 smallDataTables 做進一步的處理 foreach (var smallDataTable in smallDataTables) { PrintDataTable(smallDataTable); } } static DataTable GetOriginalDataTable() { // 這裡假設你有一個包含資料的 DataTable,你可以根據實際需求修改 DataTable originalDataTable = new DataTable(); // 假設有一個 "ID...

C#, Datatable, Join, LINQ, 子查詢

C#, Datatable, Join, LINQ, 子查詢 void Main() { DataTable dt1 = new DataTable(); dt1.Columns.Add("A", typeof(string)); dt1.Columns.Add("B", typeof(string)); dt1.Columns.Add("C", typeof(string)); dt1.Columns.Add("D", typeof(int)); // 資料填充 DataRow dr1 = dt1.NewRow(); dr1["A"] = "A1"; dr1["B"] = "B1"; dr1["C"] = "C1"; dr1["D"] = "1"; dt1.Rows.Add(dr1); dr1 = dt1.NewRow(); dr1["A"] = "A2"; dr1["B"] = "B2"; dr1["C"] = "C2"; dr1["D"] = "2"; dt1.Rows.Add(dr1); DataTable dt2 = new DataTable(); dt2.Columns.Add("E", typeof(string)); dt2.Columns.Add("F", typeof(string)); dt2.Columns.Add("G", typeof(int)); // 資料填充 DataRow dr2 = dt2.NewRow(); dr2["E"] = "A1"; dr2["F"] = "B1"; dr2["G"] = "10...

C# 撰寫擴展CLASS - DistinctBy

C# 撰寫擴展CLASS - DistinctBy void Main() { List<ClassA> list = new List<UserQuery.ClassA>(); list.Add(new ClassA() { strA = "A", strB = "A1" }); list.Add(new ClassA() { strA = "B", strB = "B1" }); list.Add(new ClassA() { strA = "B", strB = "C1" }); var a = list.DistinctBy(x => x.strA).ToList(); // strA , strB // A, A1 // B, B1 var b = list.DistinctBy(x => x.strB).ToList(); // strA , strB // A, A1 // B, B1 // B, C1 } public class ClassA { public string strA {get;set;} public string strB {get;set;} } //撰寫一個擴展CLASS public static class DistinctByClass { //方法套用在列舉上 public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { HashSet<TKey> seenKeys = new HashSet<TKey>(); foreach (TSource element in source) { if (seenKeys.Add(keySelector(el...

C# 從網頁下載檔案到指定路徑

C# 從網頁下載檔案到指定路徑 using (WebClient webClient = new WebClient()) { string FileOutput = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "abc.txt"); webClient.DownloadFile("http://abc/abc.txt", FileOutput); //儲存路徑一定要加完整路徑 }  

C# LINQ Lambda disinct (3)

C# LINQ Lambda disinct 若List< Class > 為多屬性的Class的LIST, 若對List直接下Distinct(), 無法取得預期去除重覆資料的結果。(即使所有欄位有重覆值, 也無效果) 若先select new 欄位屬性, 欄位數與原始相同也可, 再下Distinct(), 就可以達到去除重覆資料結果。 以下為範例程式, 資料結構 public class MyClass2 { public string A { get; set; } public string E { get; set; } public string F { get; set; } } List<MyClass2> list_myClass2 = new List<UserQuery.MyClass2>(); list_myClass2.Add(new MyClass2() { A = "A1", E = "E1", F = "F1" }); list_myClass2.Add(new MyClass2() { A = "A2", E = "E2", F = "F2" }); list_myClass2.Add(new MyClass2() { A = "A2", E = "E2", F = "F2" }); list_myClass2.Add(new MyClass2() { A = "A3", E = "E4", F = "F4" }); list_myClass2.Add(new MyClass2() { A = "A3", E = "E4", F = "F4" }); list_myClass2.Add(new MyClass2() { A = "A4", E = "E6", F = "F6" }); CASE-1 var query1 ...

C# 引用DLL的3種方式[靜態連結, 動態連結, 專案參考]

C# 引用DLL的3種方式 C#引用DLL的方式有 靜態連結(Static Linking) 動態連結(Dynamic Linking) 專案參考(Project Reference) 以下將說明運作原理、優/缺點... 靜態連結 運作原理, 靜態連結是將DLL編譯進應用程式的執行檔,使得應用程式與DLL的程式碼合併在一個執行檔中 優點: 執行速度較快,無需額外的DLL檔案 缺點: 更新DLL時,必須重新編譯應用程式 編譯時整合: DLL的程式碼在編譯時期被整合進入應用程式的執行檔 執行檔: 應用程式執行檔包含了所有必要的程式碼,無需額外的DLL檔案 應用範圍: 適用於相對較小且不經常更新的專案。若DLL需要更新,則必須重新編譯整個應用程式 部署方式: 部署時只需將單一執行檔複製到目標機器上,不需要額外的DLL // 使用DllImportAttribute進行靜態連結 using System.Runtime.InteropServices; class Program { // 声明 DLL 文件的路径 const string dllPath = "YourDll.dll"; // 声明 DLL 中的函数 [DllImport(dllPath)] public static extern int YourFunction(); static void Main() { // 调用 DLL 中的函数 int result = YourFunction(); Console.WriteLine($"Result from DLL: {result}"); } }   動態連結 運作原理, 在執行時期,應用程式會動態載入DLL,並使用其功能, 使用 System.Reflection 或其他方法動態調用 DLL 中的函數 優點: 更新DLL不需要重新編譯應用程式 缺點: 需要確保DLL存在於執行目錄或系統路徑 編譯時整合: DLL的程式碼在編譯時期並未整合進應用程式,僅在執行時期動態載入 執行檔: 應用程式執行檔不包含DLL程式碼,需要確保DLL存在...

List和string的Contains方法, 用法有些不同

List和string的Contains方法, 用法有些不同 List.Contains 檢查列表中是否包含指定元素, 完整比對 // 假設有一個 List<string> 包含一些字串 List<string> stringList = new List<string> { "AA", "AB", "AC", "A" }; // 檢查 List 中是否包含指定的字串 string targetString = "A"; bool containsTarget = stringList.Contains(targetString); //返回True ==> 包含"A" // 檢查 List 中是否包含指定的字串 string targetString = "C"; bool containsTarget = stringList.Contains(targetString); //返回Flase ==> 不包含"C"   string.Contains 檢查一個字串是否包含另一個字串(模糊比對) string text = "Hello, World!"; bool containsHello = text.Contains("Hello"); // 返回 true   整合範例: 使用listB找出listA有符合部份字串的資料 //變數宣告 List<string> listA = new List<string> { "ABC_123", "ABC_456", "EEE_111", "DDD_222" }; List<string> listB = new List<string> { "ABC", "EEE" }; // 使用 LINQ 查詢,找出符合條件的資料 var result = listA.Where(i...

C#, 利用dynamic宣告變數

利用dynamic宣告變數 using System; class Program { static void Main() { // 宣告 dynamic 物件 dynamic dynamicObject = new { Property1 = "Value1", Property2 = 42, Property3 = true }; // 取得屬性值 string value1 = dynamicObject.Property1; int value2 = dynamicObject.Property2; bool value3 = dynamicObject.Property3; // 顯示取得的值 Console.WriteLine($"Property1: {value1}"); Console.WriteLine($"Property2: {value2}"); Console.WriteLine($"Property3: {value3}"); } } 利用dynamic宣告空的變數, 動態指定屬性資料 using System; class Program { static void Main() { // 宣告 dynamic 變數 dynamic dynamicObject = new System.Dynamic.ExpandoObject(); // 給動態變數不同的屬性名稱和值 dynamicObject.Property1 = "Value1"; dynamicObject.Property2 = 42; dynamicObject.Property3 = true; // 讀取動態變數的屬性 string value1 = dynamicObject.Property1; int ...

C#, LINQ, 2個Table Join 使用1個欄位條件Join

using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { // 模拟两个表的数据 List<Table1> table1Data = new List<Table1> { new Table1 { Id = 1, CommonField = "A", Value = "Value1" }, new Table1 { Id = 2, CommonField = "B", Value = "Value2" }, new Table1 { Id = 3, CommonField = "C", Value = "Value3" } }; List<Table2> table2Data = new List<Table2> { new Table2 { Id = 101, CommonField = "A", Description = "Desc1" }, new Table2 { Id = 102, CommonField = "B", Description = "Desc2" }, new Table2 { Id = 103, CommonField = "D", Description = "Desc3" } }; // 使用 LINQ 进行连接操作 var query = from t1 in table1Data join t2 in table2Data on t1.Common...

C#, LINQ, 2個Table Join 使用2個欄位條件Join

2個Table Join 使用2個欄位條件Join join的欄位名稱要相同 範例1: using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { // 假设有两个表格 List<Table1> table1Data = new List<Table1> { new Table1 { ID = 1, Name = "John" }, new Table1 { ID = 2, Name = "Alice" }, new Table1 { ID = 3, Name = "Bob" } }; List<Table2> table2Data = new List<Table2> { new Table2 { ID = 1, Age = 25 }, new Table2 { ID = 2, Age = 30 }, new Table2 { ID = 3, Age = 28 } }; // 使用 LINQ 进行两个表格的连接 var query = from t1 in table1Data join t2 in table2Data on new { t1.ID, t1.Name } equals new { t2.ID, Name = "John" } select new { t1.ID, t1.Name, t2.Age }; // 打印结果 foreach (var result in query) { Console.WriteLine($...

C# Lambda List Distinct寫法(group by ... select first)

因為List<Class>要進行多欄位Distinct時, 需在Class裡Overide Equals 和 GetHashCode, 可以使用下列語法替代。參考 這篇 。 利用Group後, 取得每個Group第一組資料出來, 達到Distinct效果。 using System; using System.Collections.Generic; using System.Linq; class ClassA { public int Property1 { get; set; } public string Property2 { get; set; } public double Property3 { get; set; } public string Property4 { get; set; } public int Property5 { get; set; } } class Program { static void Main() { // 創建一個 List<ClassA> 的範例資料 List<ClassA> listOfClassA = new List<ClassA> { new ClassA { Property1 = 1, Property2 = "A", Property3 = 1.1, Property4 = "X", Property5 = 100 }, new ClassA { Property1 = 1, Property2 = "A", Property3 = 1.1, Property4 = "Y", Property5 = 101 }, new ClassA { Property1 = 2, Property2 = "B", Property3 = 2.2, Property4 = "X", Property5 = 102 }, new Cla...