Any
In this chapter you will learn:
- How to use Any operator
- Any without expression
- Any with mod operator
- Any with string operator
- How to use Any operator with custom types
Any operator
Any
returns true if the given expression
is true for at least one element.
using System;//from j a va 2 s. c o m
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
bool hasAThree = new int[] { 2, 3, 4 }.Any(n => n == 3); // true;
Console.WriteLine(hasAThree);
}
}
The output:
Any without expression
Calling Any
without an expression
returns true if the sequence has one or more elements.
Here's another way to write the preceding query:
using System;//j a v a2s . c om
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
bool hasABigNumber = new int[] { 2, 3, 4 }.Where(n => n > 10).Any();
Console.WriteLine(hasABigNumber);
}
}
The output:
Any with mod operator
using System;/* j a va2s.com*/
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
public class MainClass{
public static void Main(){
int[] numbers = { 2, 6, 1, 5, 10 };
Console.Write(numbers.Any(e => e % 2 == 1));
}
}
Any with string operator
using System;//from j av a2s. co m
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
public static void Main() {
string[] words = { "bei", "rie", "rei", "field" };
bool iAfterE = words.Any(w => w.Contains("ei"));
Console.WriteLine(iAfterE);
}
}
The following code uses All with string StartsWith method.
using System;//j av a 2s . c o m
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
public static void Main() {
string[] presidents = {"G", "H", "java2s.com", "H", "over", "Jack"};
bool any = presidents.Any(s => s.StartsWith("j"));
Console.WriteLine(any);
}
}
Any opeator and custom types
using System;//from ja v a 2 s .co m
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Customer
{
public string ID { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string Region { get; set; }
public decimal Sales { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Customer> customers = new List<Customer> {
new Customer { ID="P", City="Tehran", Country="Iran", Region="Asia", Sales=7000 },
new Customer { ID="Q", City="London", Country="UK", Region="Europe", Sales=8000 },
new Customer { ID="R", City="Beijing", Country="China", Region="Asia", Sales=9000 },
new Customer { ID="T", City="Lima", Country="Peru", Region="South America", Sales=2002 }
};
bool anyUSA = customers.Any(c => c.Country == "USA");
Console.WriteLine(anyUSA);
}
}
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » Linq Operators