在一個集合中,Select擴充方法是用來針對所下的條件,
根據該條件回傳指定型態的集合,請參考如下範例。
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
| List<Person> personCollection = new List<Person>(); personCollection.Add(new Person(1, "Tim")); personCollection.Add(new Person(2, "John")); personCollection.Add(new Person(3, "brooke"));
IEnumerable<bool> a = personCollection.Select(x => x.Id == 2); IEnumerable<Person> b = personCollection.Select(x => x); IEnumerable<int> c = personCollection.Select(x => x.Id); var carOwner = personCollection .Where(x => x.Id == 2) .Select(y => new Car { CarNo = "CAR-33456", Owner = y.Name }) .FirstOrDefault();
Console.ReadLine();
class Person { public int Id { get; set; } public string Name { get; set; } public Person(int id, string name) { Id = id; Name = name; } }
class Car { public string? CarNo { get; set; } public string? Owner { get; set; } }
|
注意,使用之前需要先include System.Linq命名空間。
參考資料:
Enumerable.Select Method