C# 通關手冊(持續更新......)

語言: CN / TW / HK

String

常用靜態方法

string.Compare(string str1,string str2,bool ignoreCase)

按照字典順序比較字符串

當str1 > str2時,返回1
當str1 = str2時,返回0
當str1 < str2時,返回-1

ignoreCase:true 忽略大小寫

string.Concat(string str1,string str2)

 string str=string.Concat("c","#"); //str="c#";

String.Format(string str)

string str=String.Format("今年是{0}年","2022");//str="今年是2022年";

string.IsNullOrEmpty(string str1)

  • 判斷字符是否為null或者為空,返回值為bool
string str2="";
bool b2=string.IsNullOrEmpty(str2);//b2=true;

string str3=null;
bool b3=string.IsNullOrEmpty(str3);//b3=true;

string.Join(string str,string[] strArr)

  • 將數組strArr中的內容拼接成一個新的字符串,並在對應數組的每兩項間添加分隔符str
string strs=string.Join(",",string[]{"w","e","r","t"});//strs="w,e,r,t";

split去重

string update_invoice = FINVO System.CollectionICENUMBER + "," + invoiceNumber; // 追加發票號
string[] oldInvoiceList = update_invoice.Split(new Char[] { ',' });
string update_invoice_str = string.Join(",", oldInvoiceList.Distinct().ToArray());

Contains

  • Contains 判斷字符串中是否包含某個字符,返回bool值
string str="我愛編程";
bool b=str.Contains("程");//b=true;

StartsWith/EndsWith

string str="我好喜歡你";

bool b1=str.StartsWith("好");//b1=false;

bool b2-str.EndsWith("你");//b2=true;

Equals

string str1="asd";
string str2="ert";

bool  b = str1.Equals(str2);  //b=false;
bool <strName>.Equals(string str, StringComparison.OrdinalIgnoreCase)   //表示不區分大小寫

IndexOf/LastIndexOf

  • 判斷字符串第一次出現(IndexOf)和最後一次出現(LastIndexOf )的位置,如果沒有出現過則返回值為-1
string str ="今天的雨很大,天很冷";

int i=str.IndexOf("很"); //i=4;
int i=str.LastIndexOf("很");//j=8;
int m=str.IndexOf("小");//m=-1;

Replace

string str="好睏呀";
string s=str.Replace("困","精神");//s="好精神呀";

Insert

  • 在字符串的index位置上插入字符,原來的字符依次後移,變成一個新的字符串
string str="夜深了";
string s=str.Insert(1,"已經");// s="夜已經深了"

Remove

  • 在字符串中移除從startIndex開始,長度為length的字符串,剩下的字符合為一個新的字符串( = .Remove(startIndex,length):wink:
string str="夜已經深了";
string s=str.Remove(1,2);//s="夜深了";

Split

  • 將字符串 以sep數組中的字符分割,分割後得到的內容存到一個數組中(string[] .Split(params char[] sep);)
string str="我,真的、好睏;呀";
string[] s=str.Split(new char(){',','、',';'});//s=string[]{"我","真的","好睏","呀"};

Substring

  • 取字符 以index開始截取,並截取lenth個字符(string .Substring(index,lenth))
string str="還在下雨";
string s=str.Substring(2,2);//s="下雨";

ToCharArray

  • 將字符串轉化為字符數組( .ToCharArray())
string str="雨已經小了";
char[] s=str.ToCharArray();//s=char[]{'雨',"已","經","小","了"};

Trim

  • 出去兩邊的空格
string str=" aa ";
string s=str.Trim();//s="aa";

ToUpper/ToLower

  • ToUpper(轉換為大寫)和ToLower(轉換為小寫)
string s="RaSer";
string s1=s.ToUpper();//s1="RASER";
string s2=s.ToLower();//s2="raser";

API

屬性

方法

List

創建List

using System.Collections.Generic;
List<string> list = new List<string>();
list.Add("a");

數組去重

using System;
using System.Collections.Generic;
using System.Linq;

List<string> list1 = new List<string>() {"123","456","789","789" };// ["123","456","789","789"]
List<string> newList =  list1.Distinct().ToList(); //["123","456","789"]

數組是否包含

using System;
using System.Collections.Generic;
using System.Linq;

List<string> list1 = new List<string>() {"123","456","789","789" };// ["123","456","789","789"]
if(list1.Contains("123")){
	 Console.WriteLine(true);
}else{
	 Console.WriteLine(false);
}

數組分組

using System;
using System.Collections.Generic;
using  System.Linq;

List<int>  sqlList = new List<int>();
for(int i=0;i<100;i++){
	sqlList.Add(i);
}

Console.WriteLine(sqlList.ToString());
List<List<int>> sql_batch = sqlList.Select((x, i) => new { Index = i, Value = x })
			.GroupBy(x => x.Index / 5) //分成5組
			.Select(x => x.Select(v => v.Value).ToList())
			.ToList();
Console.WriteLine(sql_batch.ToString());

API

屬性

方法

HashTable

  • 線程安全,單線程性能不如Dictionary

創建Map

using System;  
using System.Collections;

Hashtable table =  new  Hashtable();
//添加的是鍵值對 
table.Add("name",  "zhangsan"); 
table.Add("age",  10); 
table.Add("gender",  "male");

刪除指定鍵的元素

using System;
using System.Collections;

Hashtable table =  new  Hashtable();
table.Add("age",  10);
//通過Key來刪除一個鍵值對 
table.Remove("age");

修改元素

using System;
using System.Collections;

Hashtable table =  new  Hashtable();
table.Add("age",  10);
//通過Key來修改元素
table["age"]  =  30;

遍歷Keys

using System;
using System.Collections;

Hashtable table =  new  Hashtable();
//添加的是鍵值對 
table.Add("name",  "zhangsan");
table.Add("age",  10);
table.Add("gender",  "male");
ICollection keys = table.Keys;
//遍歷剛剛獲取到的所有的Key
foreach (object key in keys)
{
    //通過Key來獲取Value
    Console.WriteLine($"{key}={table[key]}");
}

遍歷Keys-Values

using System;  
using System.Collections;

Hashtable table =  new  Hashtable();
//添加的是鍵值對 
table.Add("name",  "zhangsan"); 
table.Add("age",  10); 

//Hashtable中存儲的元素類型是DictionaryEntry
foreach (DictionaryEntry entry in table)
{
   //獲取一個鍵值對中的鍵
   object key = entry.Key;
   //獲取一個鍵值對中的值
   object value = entry.Value;
   Console.WriteLine($"{key}={value}");
}

獲取HashTable中的鍵值對的數目

using System;
using System.Collections;

Hashtable table =  new  Hashtable();
int Count = table.Count;

清空集合

using System;  
using System.Collections;

Hashtable table =  new  Hashtable();
table.Clear();

判斷Hashtable中是否包含了指定的鍵

using System;  
using System.Collections;

Hashtable table =  new  Hashtable();
//添加的是鍵值對 
table.Add("name",  "zhangsan"); 
table.Add("age",  10); 
bool result = table.Contains("age");

Dictionary

創建Map

using System.Collections.Generic;

Dictionary<int,string > dict = new Dictionary<int,string>();

dict.Add(1,"111");

dict.Add(2,"222");

刪除指定鍵的元素

using System.Collections.Generic;

Dictionary< string , int > d = new Dictionary< string , int >();
d.Add( "C#" , 2);
d.Add( "VB" , 1);
d.Add( "C" , 0);
d.Add( "C++" , -1);
//刪除鍵為“C”的元素
d.Remove( "C" );
//刪除鍵為“VB”的元素
d.Remove( "VB" );

序列化為JSON對象

using Newtonsoft.Json;
using System.Collections.Generic;

Dictionary<string, int> dic = new Dictionary<string, int>() {
    {"張三",1},
    {"李四",2},
};
string result = JsonConvert.SerializeObject(dic);
Console.WriteLine(result); //{"張三":1,"李四":2}

JSON對象反序列化Dictionary

using Newtonsoft.Json;
using System.Collections.Generic;

result = "{\"張三\":1,\"李四\":2}";
Dictionary<string, int> dic2 = JsonConvert.DeserializeObject<Dictionary<string, int>>(result);
foreach (var item in dic2)
{
    Console.WriteLine($"{item.Key}---->{item.Value}");
}

判斷是否存在相應的key並顯示

using System.Collections.Generic;

Dictionary<int,string > dict = new Dictionary<int,string>();
if (dict.ContainsKey(<key>))
 {
	 Console.WriteLine(dict[<key>]);
 }

遍歷Keys

using System.Collections.Generic;

Dictionary<int,string > dict = new Dictionary<int,string>();
foreach (var item in dict.Keys)
{
 Console.WriteLine( "Key:{0}" , item);
}

遍歷Values

using System.Collections.Generic;

Dictionary<int,string > dict = new Dictionary<int,string>();
foreach (var item in dict.Values)
{
 Console.WriteLine( "value:{0}" , item);
}

遍歷整個字典

using System.Collections.Generic;

Dictionary<int,string > dict = new Dictionary<int,string>();
foreach (var item in dict)
{
 Console.WriteLine( "key:{0} value:{1}" , item.Key, item.Value);
}

HashSet

  • 高性能且無序的集合,只能使用foreach來進行迭代,而無法使用for循環。

創建HashSet

using System; 
using System.Collections.Generic;
HashSet<string> hashSet = new HashSet<string>();
hashSet.Add("A");
hashSet.Add("B");
hashSet.Add("C");
hashSet.Add("D");

// A B C D

判斷是否包含

hashSet.Contains("D")

移除某元素

hashSet.Remove(item);

刪除所有元素

hashSet.Clear()

判斷 HashSet 是否為某一個集合的完全子集

HashSet<string> setA = new HashSet<string>() { "A", "B", "C", "D" };
HashSet<string> setB = new HashSet<string>() { "A", "B", "C", "X" };
HashSet<string> setC = new HashSet<string>() { "A", "B", "C", "D", "E" };
if (setA.IsProperSubsetOf(setC)) //是子集輸出1,不是輸出0
   Console.WriteLine("setC contains all elements of setA.");
if (!setA.IsProperSubsetOf(setB))
   Console.WriteLine("setB does not contains all elements of setA.");

集合合併

  • 輸出setA setB中的所有元素
using System; 
using System.Collections.Generic;

HashSet<string> setA = new HashSet<string>() { "A", "B", "C", "D", "E" };
HashSet<string> setB = new HashSet<string>() { "A", "B", "C", "X", "Y" };
setA.UnionWith(setB);
foreach(string str in setA)
{
   Console.WriteLine(str);
}
//最終setA的輸出結果是 A B C D E X Y

交集

  • 輸出setA和setB集合中都有的元素
using System; 
using System.Collections.Generic;

HashSet<string> setA = new HashSet<string>() { "A", "B", "C", "D", "E" };
HashSet<string> setB = new HashSet<string>() { "A", "B", "C", "X", "Y" };
setA.IntersectWith(setB);
// A B C

差集

  • 輸出setA集合中有但setB集合中沒有的元素
using System;
using System.Collections.Generic;

HashSet<string> setA = new HashSet<string>() { "A", "B", "C", "D", "E" };
HashSet<string> setB = new HashSet<string>() { "A", "B", "C", "X", "Y" };
setA.ExceptWith(setB);
// D E

兩個集合都不全有的元素

HashSet<string> setA = new HashSet<string>() { "A", "B", "C", "D", "E" };
HashSet<string> setB = new HashSet<string>() { "A", "X", "C", "Y" };
setA.SymmetricExceptWith(setB);
foreach (string str in setA)
{
  Console.WriteLine(str);
}
//對於這個示例,最終輸出結果是BDEXY

SortedSet

創建SortedSet

using System;
using System.Collections.Generic;

SortedSet<string> set1 = new SortedSet<string>();
set1.Add("CD");
set1.Add("CD");
set1.Add("CD");
set1.Add("CD");
Console.WriteLine("Elements in SortedSet1...");
foreach (string res in set1) {
		Console.WriteLine(res);
}

API

Json

創建JSON

金蝶JSON

using Kingdee.BOS.JSON;
JSONObject jsonObject = new JSONObject();
jsonObject.Put("userName", dynamicObjectCollection[0]["USERNAME"]);
jsonObject.Put("reason", backMsg);
jsonObject.Put("bbcOrderNum",billNo);

C# JSON

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
JObject jObject = new JObject();
jObject["recMobile"] = Convert.ToString(dynamicObject["FReceiverPhone"]);
jObject["recTel"] = Convert.ToString(dynamicObject["FReceiverTel"]);

合併其他對象到屬性

JObject obj = new JObject();
obj.Add("name", "張三");
obj.Add("birthday", DateTime.Now);
 
//合併其他對象到當前對象的屬性
obj.Add("content", JToken.FromObject(new
{
    code = "zhangsan"
}));


//返回
{
	"name":"張三",
	"birthday","2022-05-04",
	"content":{
		"code":"zhangsan"
	}
}

合併其他對象的屬性,到當前對象

//合併其他
JObject obj = new JObject();
obj.Add("name", "張三");
obj.Add("birthday", DateTime.Now);

JObject obj2 = JObject.FromObject(new
{
    code = "lisi"
});
obj.Merge(obj2);

//返回
{
	"name":"張三",
	"birthday","2022-05-04",
	"code ":"lisi"
}

JSON解析

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

string jsonText = @"{
 "input": {
	'size': 193156, 
	'type': 'image/png'
}";
JObject jobject = (JObject)JsonConvert.DeserializeObject(jsonText);
decimal input_size = Convert.ToDecimal(jobject["input"]["size"]);//193156, 輸入圖片大小
string input_type = jobject["input"]["type"].ToString();// "image/png",輸入圖片類型

DateTime

字符串轉時間

DateTime time= Convert.ToDateTime("2022-04-28 00:00:00");
Console.WriteLine(time);

時間轉字符串

DateTime dt_now = DateTime.Now;
string time=dt_now.ToString("yyyy-MM-dd hh:mm:ss");
Console.WriteLine(time);

時間字符串格式化 yyyy-MM-dd hh:mm:ss 轉 yyMMdd

string time = Convert.ToDateTime("2019-08-28 00:00:00").ToString("yyMMdd");
Console.WriteLine(time);

Thread

創建多線程 無參

//threadMain
Console.WriteLine("Main方法開始執行...");
Thread threadA = new Thread(Execute);
threadA.Start();

Thread threadB = new Thread(test);
threadB.Start();
Console.WriteLine("Main方法執行結束...");

//threadB
private void test() {
   while (true) {
   Console.WriteLine($"test:{DateTime.Now.Ticks}");
   }
}

//threadA
private void Execute() {
   Console.WriteLine("開始下載,此協程的Id是:" +            Thread.CurrentThread.ManagedThreadId);
  int bill_count = billNoList.Count;
  Thread.Sleep(5000 * bill_count);
  foreach (string billNo in billNoList)
  {
    getIvnumber(billNo);
  }
  Console.WriteLine("下載完成");
}

創建多線程 帶參

//定義一個類,用於存放線程需要的數據和線程啟動的方法
public class MyThread
{
  private string data;//線程數據

  public MyThread(string data)
  {
    this.data = data;
  }
  //線程啟動方法
  public void ThreadMain()
  {
    Console.WriteLine("Running in a thread, data: {0}", data);
  }
}
static void Main()
{
  MyThread obj = new MyThread("info");//創建實例信息
  Thread t3 = new Thread(obj.ThreadMain);//啟動實例方法
  t3.Start();
}
//定義一個數據類型,傳遞給線程
public struct Data
{
  public string Message;
}
//創建一個方法,將方法給線程的ParameterizedThreadStart委託
static void ThreadMainWithParameters(object obj)
{
  Data d = (Data)obj;
  Console.WriteLine("Running in a thread, received {0}", d.Message);
}
static void Main()
{
  Data d = new Data { Message = "Info" };//創建一個數據實例
  Thread t2 = new Thread(ThreadMainWithParameters);//創建線程
  t2.Start(d);//啟動線程,並傳遞參數
}

線程啟動 前台線程/後台線程

//前台線程
//創建線程方法,以在主線程中調用
static void ThreadMain()
{
  Console.WriteLine("Thread {0} started", Thread.CurrentThread.Name);
  Thread.Sleep(3000);
  Console.WriteLine("Thread {0} completed", Thread.CurrentThread.Name);
}
static void Main()
{
  Thread t1 = new Thread(ThreadMain);  t1.Name = "MyNewThread";
  t1.Start();   Thread.Sleep(100);
  Console.WriteLine("Main thread ending now...");
  /*******************輸出********************     *          Thread MyNewThread started
   *     Main thread ending now...
   *     Thread MyNewThread completed
   * *****************************************/
}
//後台線程
static void Main()
{
  Thread t1 = new Thread(ThreadMain);
  t1.Name = "MyNewThread";
  t1.IsBackground = true;
  t1.Start();
  Thread.Sleep(100);
  Console.WriteLine("Main thread ending now...");
  /*******************輸出********************
   *     Thread MyNewThread started
   *     Main thread ending now...
   * *****************************************/
}
前台線程:主線程默認啟動方式為前台線程,主線程結束後,前台線程仍可以活動。
後台線程:如果在線程啟動前,將線程的IsBackground屬性設置為true,主線程結束時,會終止新線程的執行(不論是否完成任務)。

Ramdom

生成隨機數

using System;

Random r = new Random();
Console.WriteLine(r.Next(1,5));