本文整理汇总了C#中System.Linq.Enumerable.Any方法的典型用法代码示例。如果您正苦于以下问题:C# Enumerable.Any方法的具体用法?C# Enumerable.Any怎么用?C# Enumerable.Any使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。
在下文中一共展示了Enumerable.Any方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1:
List<int> numbers = new List<int> { 1, 2 };
bool hasElements = numbers.Any();
Console.WriteLine("The list {0} empty.",
hasElements ? "is not" : "is");
输出:
The list is not empty.
示例2: AnyEx2
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
class Person
{
public string LastName { get; set; }
public Pet[] Pets { get; set; }
}
public static void AnyEx2()
{
List<Person> people = new List<Person>
{ new Person { LastName = "Haas",
Pets = new Pet[] { new Pet { Name="Barley", Age=10 },
new Pet { Name="Boots", Age=14 },
new Pet { Name="Whiskers", Age=6 }}},
new Person { LastName = "Fakhouri",
Pets = new Pet[] { new Pet { Name = "Snowball", Age = 1}}},
new Person { LastName = "Antebi",
Pets = new Pet[] { }},
new Person { LastName = "Philips",
Pets = new Pet[] { new Pet { Name = "Sweetie", Age = 2},
new Pet { Name = "Rover", Age = 13}} }
};
// Determine which people have a non-empty Pet array.
IEnumerable<string> names = from person in people
where person.Pets.Any()
select person.LastName;
foreach (string name in names)
{
Console.WriteLine(name);
}
/* This code produces the following output:
Haas
Fakhouri
Philips
*/
}
示例3: AnyEx3
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
public bool Vaccinated { get; set; }
}
public static void AnyEx3()
{
// Create an array of Pets.
Pet[] pets =
{ new Pet { Name="Barley", Age=8, Vaccinated=true },
new Pet { Name="Boots", Age=4, Vaccinated=false },
new Pet { Name="Whiskers", Age=1, Vaccinated=false } };
// Determine whether any pets over age 1 are also unvaccinated.
bool unvaccinated =
pets.Any(p => p.Age > 1 && p.Vaccinated == false);
Console.WriteLine(
"There {0} unvaccinated animals over age one.",
unvaccinated ? "are" : "are not any");
}
输出:
There are unvaccinated animals over age one.