Select 將序列中的每個元素投影為新形式,可回傳屬性、新物件、匿名型別、方法呼叫結果等。方法原型:
public static IEnumerable Select(
this IEnumerable source, Func selector)
// 選取屬性
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();
將序列中每個元素投影為 IEnumerable<T> 並合併為單一序列。原型:
public static IEnumerable SelectMany(
this IEnumerable source, Func> selector)
// 方法語法
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。