判空

?and ??

1
2
3
4
int i; //默认值0
int? ii; //默认值null
string str = null;
str = str??"" // ??判断若为空则返回某值

?. and ??

  • ?. 为空就执行方法,常用事件传递,_action?.Invork()
  • ?? 为空就赋值

Guard.IsNotNull

  • 空异常抛出,若为空就抛异常,否则通过

Is and As

if(xxx is aaa x) bbb;
var x = a as c;
if (x != null) xxx

字符串常用API

拼接

1
2
3
4
5
6
7
// Format 插值方法
String s = String.Format("The current price is {0} per ounce.", price);

// ${}
String s = $"{The current price is {0} per ounce}";

// + 加号的方法每次都new出新的字符串进行拼接,尽量不用

分割

1
2
3
String str = "1,2,3,4";
String[] s = str.split(",");
// 按参数分割,返回一个Array

字典常用API

  • TryGetValue:通过键找是否有对应的键值对

时间表示

1
2
var dt = DateTime.Now;
notice.NoticeID = string.Format("{0:yyyyMMdd}{1}", dt, i++.ToString("00"));

Linq

常用

  • any 是否有

  • orderby 升序

  • distinct 去重

  • take 保留前几个

  • skip 跳过前几个

1
2
3
4
5
6
7
8
9
var list = new List<int>();

//比如 list里面是 1,2,3,4,5,6,7,8,9,10

var result = list.Skip(2); //返回值就是 3,4,5,6,7,8,9,10;

var result = list.Take(2); //返回值就是 1,2

var result = list.Skip(2).Take(2); //返回值 3,4
  • SkipWhile 按条件跳过

  • thenby … 多次排序

二维数组去重

1
2
3
// 二维数组删除重复
decoder.DecodeFile(folder, fileName, out _, out _, out _, out var valueLines);
var dic1 = valueLines.DistinctBy(x => x[0]);

序列化

ToJson()
DeserializeObject 序列化 转成string

向上向下取整

1
2
double down = Math.Floor(77.5);  //向下取整 77
double up = Math.Ceiling(77.5); //向上取整 78

default(T)关键字

  • C# 在类初始化时,会给未显示赋值的字段、属性赋上默认值,但是值变量却不会。

  • 值变量可以使用默认构造函数赋值,或者使用default(T)赋值。

  • 默认构造函数是通过 new 运算符来调用的,如下所示:

1
2
3
4
5
int myInt = new int();

int myInt = default(int);

int myInt = 0;

在 C# 中不允许使用未初始化的变量

————————————————

From:https://blog.csdn.net/lizhenxiqnmlgb/article/details/81476115