c# Linq語法很有趣也很好用
- 建立物件之後,把物件置入List內使用。
- 使用Where() Max() Min()進行查詢。
- 使用 Take 拿取n個。
- 使用 foreach 列出資料。
var Users = new List<User>
{
new User{ Id = 1, Name = "Atsai", Age = 25},
new User{ Id = 2, Name = "Biran", Age = 36},
new User{ Id = 3, Name = "Gray", Age = 32},
new User{ Id = 4, Name = "Vitra", Age = 33},
new User{ Id = 5, Name = "Fito", Age = 22},
new User{ Id = 6, Name = "Lido", Age = 34}
};
var User_oldest = Users.Where(x => x.Age == Users.Max(x => x.Age) );
var User_youngest = Users.Min(x => x.Age);
var User_3User = Users.Take(3);
Console.WriteLine("User_3User:");
foreach (User u in User_3User)
{
Console.WriteLine($"Id:{u.Id} , Name:{u.Name} , Age:{u.Age} ");
}
Console.WriteLine("Users:");
foreach (User u in Users)
{
Console.WriteLine($"Id:{u.Id} , Name:{u.Name} , Age:{u.Age} ");
}
Console.WriteLine("User_oldest");
foreach (User u in User_oldest)
{
Console.WriteLine($"Id:{u.Id} , Name:{u.Name} , Age:{u.Age} ");
}
Console.WriteLine("User_youngest:");
Console.WriteLine( User_youngest.ToString() );
public class User
{
public int Id { get; set; }
public string? Name { get; set; }
public int Age { get; set; }
}
執行結果如下:
User_3User:
Id:1 , Name:Atsai , Age:25
Id:2 , Name:Biran , Age:36
Id:3 , Name:Gray , Age:32
Users:
Id:1 , Name:Atsai , Age:25
Id:2 , Name:Biran , Age:36
Id:3 , Name:Gray , Age:32
Id:4 , Name:Vitra , Age:33
Id:5 , Name:Fito , Age:22
Id:6 , Name:Lido , Age:34
User_oldest:
Id:2 , Name:Biran , Age:36
User_youngest:
22