記錄C#語法的使用

記錄一下C#的用法

C# 6 的三個新的表示式

介紹 C# 6 的三個新語法:nameof 表示式、字串插值、和 null 條件運算子。

  1. nameof 表示式
    C# 6 新增的 nameof 關鍵字可用來取得某變數的名稱。請看底下這個簡單範例,便能了解其作用:
1
2
string firstName = "Joey";
string varName = nameof(firstName); // 編譯結果:varName = "firstName"

比如說,為了防錯,我們經常在函式中預先檢查參數值是否合法,並將不合法的參數透過拋異常(exception)的方式通知呼叫端(或者寫入 log 檔案以供將來診斷問題)。像這樣:

1
2
3
4
5
6
7
void LoadProduct(string productId)
{
if (productId == null)
{
throw new ArgumentNullException(nameof(productId));
}
}
  1. 字串插值
    NET Framework 提供的字串格式化方法 String.Format(…) 是一種對號入座的寫法,相當好用。
    現在,C# 6 提供了另一種格式化字串的寫法,名曰「字串插值」(string interpolation)。
    $”{變數名稱:格式規範}”

    1
    2
    3
    4
    5
    6
    7
    8
    string firstName = "Michael";
    string lastName = "Tsai";
    int salary = 22000;

    string msg1 = String.Format("{0} {1} 的月薪是 {2:C0}", firstName, lastName, salary);
    string msg2 = $"{firstName} {lastName} 的月薪是 {salary :C0}";
    Console.WriteLine(msg1);
    Console.WriteLine(msg2);
  2. Null 條件運算子
    保險起見,在需要存取某物件的屬性之前,我們通常會先檢查該物件是否為 null

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    static void NullPropagationDemo(string s)
    {
    if (s?.Length == 4) // 只有當 s 不為空時才存取它的 Length 屬性。
    {
    // Do something.
    }
    }

    int? length = productList?.Length; // 若 productList 是 null,則 length 也是 null。
    Customer obj = productList?[0]; // 若 productList 是 null,則 obj 也是 null。
    int length = productList?.Length ?? 0; // 若 productList 是 null,則 length 是 0。
    string name = productList?[0].FullName; // 若 productList 是 null,則 name 是 null。

有關json的用法

字串轉json物件,json物件轉字串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
public static void strJson()
{
string jsonText = "{\"shenzheng\":\"深圳\",\"beijing\":\"北京\",\"shanghai\":[{\"zj1\":\"zj11\",\"zj2\":\"zj22\"},\"zjs\"]}";
//转为json对象
JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText);
string zone = jo["shenzheng"].ToString();//输出 深圳
string zone_en = jo["shanghai"].ToString();//"[\r\n {\r\n \"zj1\": \"zj11\",\r\n \"zj2\": \"zj22\"\r\n },\r\n \"zjs\"\r\n]"
string zj1 = jo["shanghai"][1].ToString();//"zjs"
Console.WriteLine(jo);
}
//对象与数组转JSON
public static void GetJsonString()
{
//初始化对象
Obj product = new Obj() { Name = "苹果", Price = 5.5 };
//序列化
string o = new JavaScriptSerializer().Serialize(product);//值:"{\"Name\":\"苹果\",\"Price\":5.5}"



//数组转json
List<Obj> products = new List<Obj>(){
new Obj(){Name="苹果",Price=5.5},
new Obj(){Name="橘子",Price=2.5},
new Obj(){Name="干柿子",Price=16.00}
};

ProductList productlist = new ProductList();
productlist.GetProducts = products;
//序列化
string os = new JavaScriptSerializer().Serialize(productlist);
//输出 "{\"GetProducts\":[{\"Name\":\"苹果\",\"Price\":5.5},{\"Name\":\"橘子\",\"Price\":2.5},{\"Name\":\"干柿子\",\"Price\":16}]}"
}

//json转对象、数组, 反序列化
public static void JSONStringToList()
{

//json格式字符串
string JsonStr = "{Name:'苹果',Price:5.5}";
JavaScriptSerializer Serializer = new JavaScriptSerializer();

//json字符串转为对象, 反序列化
Obj obj = Serializer.Deserialize<Obj>(JsonStr);
Console.Write(obj.Name + ":" + obj.Price + "\r\n");



//json格式字符串
string JsonStrs = "[{Name:'苹果',Price:5.5},{Name:'橘子',Price:2.5},{Name:'柿子',Price:16}]";

JavaScriptSerializer Serializers = new JavaScriptSerializer();

//json字符串转为数组对象, 反序列化
List<Obj> objs = Serializers.Deserialize<List<Obj>>(JsonStrs);

foreach (var item in objs)
{
Console.Write(item.Name + ":" + item.Price + "\r\n");
}
}

分組的用法

過去面對這種問題,我慣用的做法先定義一個Dictionary<string, List>,使用 foreach 逐筆抓取來源資料
foreach + Dictionary寫法用了好幾年,前幾天才忽然想到,這不就是SQL語法中的GROUP BY嗎?加上LINQ有ToDictionary, GroupBy(o => o.客戶編號).ToDictionary(o => o.Key, o => o.ToList()) 一行就搞定了呀!阿呆。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace LinqTip
{
class Program
{
public enum Teams
{
Valor, Mystic, Instinct, Dark
}
 
public class Trainer
{
public Teams Team;
public string Name;
public Trainer(Teams team, string name)
{
Team = team; Name = name;
}
}
 
static void Main(string[] args)
{
//來源資料如下
List<Trainer> trainers = new List<Trainer>()
{
new Trainer(Teams.Valor, "Candela"),
new Trainer(Teams.Valor, "Bob"),
new Trainer(Teams.Mystic, "Blanche"),
new Trainer(Teams.Valor, "Alice"),
new Trainer(Teams.Instinct, "Spark"),
new Trainer(Teams.Mystic, "Tom"),
new Trainer(Teams.Dark, "Jeffrey")
};
//目標:以Team分類,將同隊的訓練師集合成List<Trainer>,
//最終產出Dictionary<Teams, List<Trainer>>
 
//以前的寫法,跑迴圈加邏輯比對
var res1 = new Dictionary<Teams, List<Trainer>>();
foreach (var t in trainers)
{
if (!res1.ContainsKey(t.Team))
res1.Add(t.Team, new List<Trainer>());
res1[t.Team].Add(t);
}
 
//新寫法,使用LINQ GroupBy
var res2 =
trainers.GroupBy(o => o.Team)
.ToDictionary(o => o.Key, o => o.ToList());
}
}
}
參考