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)?
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

属性

image

方法

imageimageimage

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

属性

image

方法

image

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

image

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));
C#
作者:|brucejiao|,原文链接: https://www.cnblogs.com/brucejiao/p/16188865.html

文章推荐

kafka集群是如何选择leader,你知道吗?

从零开始使用 Astro 的实用指南

【性能】JDK和Jmeter的安装与配置

SpringBoot 配置CORS处理前后端分离跨域配置无效问题解析

ResNet50的猫狗分类训练及预测

如何通过Java代码将添加页码到PDF文档?

Java BIO,NIO,AIO

js中null和undefined的区别

Linux进程通信 | 消息队列

idea 调试小心得

HTTP面试题 - HTTP2 面试题

springboot如何使用自定义配置文件