Generics 是在 C# 2.0 時所新增加的類型,再 2.0 時就已經感受到他的好處了,最近把之前寫的程式又拿出來看時,就想說把改成 3.0 的格式好了,再著手進行的過程中,更感受到 C# 3.0 的強大的功能。讓以前要寫很多行來表示的敘述,通通變成一行就搞定了,以下就簡單的做個筆記,以免我自己忘記。(因為寫的更好的...人大有人在…噗~)

為了簡單介紹,我需要一個 Class,此 Class 為 Employee:

public class Employee
{
    public string Name { get; set; }

    public int ID { get; set; }

    public double Salary { get; set; }
}

 

現在我們建立一個 Employee 的 List 集合

List<Employee> Employees = new List<Employee>();

Employees.Add(new Employee { Name = "Willy", ID = 0001, Salary = 35000 });
Employees.Add(new Employee { Name = "Yummi", ID = 0002, Salary = 30000 });
Employees.Add(new Employee { Name = "Miri", ID = 0003, Salary = 22000 });

 

接下來就針對不同的目的來簡單的說明,其中我們將使用到 Lambda 的表示方式來呈現

排序

// 沿用 2.0 的 delegate 的方式
Employees.Sort((emp1, emp2) => emp1.Salary.CompareTo(emp2.Salary));

// 3.0 新的方式
//由小到大
IEnumerable orderedEmp1 = Employees.OrderBy(emp => emp.Salary);
//由大到小
IEnumerable orderedEmp2 = Employees.OrderByDescending(emp => emp.Salary);

 

條件式的搜尋

//收尋薪水大於 20K 的員工
IEnumerable EmpsWithBigSalary = Employees.Where((emp) => emp.Salary > 20000);

//使用 Linq
IEnumerable EmpsWithBigSalarybyLinq = from Employee emp in Employees
                                      where emp.Salary > 20000
                                      select emp;

 

差異

//扣除薪水大於 20K 的員工
IEnumerable ExceptEmps = Employees.Except(EmpsWithBigSalary);

 

唯一

//取的唯一的值
IEnumerable DistinctEmps = Employees.Distinct();

 

轉換成 List

//將 Name 轉成 List
IEnumerable empNames = Employees.Select((emp) => emp.Name);
//將 ID 轉成 List
IEnumerable empIDs = Employees.Select((emp) => emp.ID);

 

 

以上是最近的案子常常用到的功能,關於其他的 Function,可在官方網站上找到相關的說明:

Enumerable Methods

Generics (C# Programming Guide)

Delegates (C# Programming Guide)

LINQ Query Expressions (C# Programming Guide)


arrow
arrow
    全站熱搜

    王圓外 發表在 痞客邦 留言(2) 人氣()