星期六, 6月 04, 2022

[LINQ] ANY、All

平時常用 any(),突然用到 all() 時腦袋有點打結,根據官方文章來練習並記錄兩者差異

Determines whether all elements of a sequence satisfy a condition. 
Determines whether any element of a sequence exists or satisfies a condition.
在 LinqPad 上練習
void Main()
{

	GetData().Where(p => p.Pets.Any() == false)
		.Select(p => p.LastName)
		.Dump("沒有飼養寵物的人");

	GetData().Single(p => p.LastName == "Philips")
		.Pets.Any(pet => pet.Age > 1 && pet.Vaccinated == false)
		.Dump("Philips 是否有寵物超過 1 歲還沒打疫苗");

	GetData().Single(p => p.LastName == "Haas")
		.Pets.All(pet => pet.Name.StartsWith("B"))
		.Dump("Haas 的寵物名稱,是否都是 B 開頭");

	GetData().Where(p => p.Pets.Any() && p.Pets.All(pet => pet.Age > 5))
		.Select(p => p.LastName)
		.Dump("有飼養寵物,且年紀都在 5 歲以上的飼主");

	List<Person> GetData()
	{
		return new List<Person>
		{
			new Person { LastName = "Haas" , 
				Pets = new Pet[] {  
					new Pet { Name = "Barley"   , Age = 10 , Vaccinated = true},
					new Pet { Name = "Boots"    , Age = 14 , Vaccinated = true},
					new Pet { Name = "Whiskers" , Age = 6  , Vaccinated = true}}},
				
		  	new Person { LastName = "Fakhouri" , 
				Pets = new Pet[] {  
					new Pet { Name = "Snowball" , Age = 1  , Vaccinated = false}}},
				
		  	new Person { LastName = "Antebi" , 
				Pets = new Pet[] {
					new Pet { Name = "Belle"    , Age = 8  , Vaccinated = true}}},
				
		  	new Person { LastName = "Philips" , 
				Pets = new Pet[] {
					new Pet { Name = "Sweetie"  , Age = 2  , Vaccinated = false},
					new Pet { Name = "Rover"    , Age = 13 , Vaccinated = true}}},
					
			// 該位沒有飼養寵物
			new Person { LastName = "NoName",
				Pets = new Pet[] { }},
		};
	}
}

class Pet
{
	public string Name { get; set; }
	public int Age { get; set; }
	public bool Vaccinated { get; set; }
}

class Person
{
	public string LastName { get; set; }
	public Pet[] Pets { get; set; }
}

[LINQ] ANY、All 

沒有留言:

張貼留言