首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

LINQ 學習筆記 (四) 投影、篩選與排序操作

     編輯:關於C語言

Select 投影操作

Select 將序列中的每個元素投影為新形式,可回傳屬性、新物件、匿名型別、方法呼叫結果等。方法原型:

public static IEnumerable Select(
    this IEnumerable source, Func selector)

Select 多種用法範例

// 選取屬性
var names = from student in DataSource.Students
            where student.Name.Length > 3
            select student.Name;

// 選取整個物件
var students = from student in DataSource.Students
               where student.Name.Length > 3
               select student;

// 選取新建立的具名型別
var newStudents = from student in DataSource.Students
                  where student.Name.Length > 3
                  select new Student { Name = student.Name, StudentID = student.StudentID };

// 選取匿名型別
var anon = from student in DataSource.Students
           where student.Name.Length > 3
           select new { Name = student.Name, StudentID = student.StudentID };

// 對結果呼叫方法
var strings = from student in DataSource.Students
              where student.Name.Length > 3
              select student.ToString();

SelectMany 扁平化投影

將序列中每個元素投影為 IEnumerable<T> 並合併為單一序列。原型:

public static IEnumerable SelectMany(
    this IEnumerable source, Func> selector)

SelectMany 範例:取得所有學生姓名的字元序列

// 方法語法
var chars = DataSource.Students.SelectMany(s => s.Name);

// 查詢語法(雙 from)
var chars = from student in DataSource.Students
            from ch in student.Name
            select ch;

string 實作 IEnumerable<char>,故可直接用於 SelectMany。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved