Using C# LINQ - A Practical Overview
player_one
1694.8K views
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Any(<predicate>) method
Returns true
if at least one of the elements in the source sequence matches the provided predicate. Otherwise it returns false
.
IEnumerable<double> doubles = new List<double> { 1.2, 1.7, 2.5, 2.4 };
// Will return false
bool result = doubles.Any(val => val < 1);
NOTE:
Any()
can also be called without a predicate, in which case it will returntrue
if there is at least one element in the source sequence.
All(<predicate>) method
Returns true
if every element in the source sequence matches the provided predicate. Otherwise it returns false
.
IEnumerable<string> strings = new List<string> { "one", "three", "five" };
// Will return true
bool result = strings.All(str => str.Contains("e"));
Any() / All() quiz
string result = "none";
IEnumerable<string> strings = new List<string> { "four", "one", "two", "three", "five" };
if (strings.Take(3).Any(s => s.StartsWith("a")))
{
if (strings.Skip(1).Take(2).All(s => s.Length == 3))
{
result = "red";
}
else
{
result = "orange";
}
}
else
{
if (strings.All(s => s.Length > 2))
{
if (strings.OrderBy(s => s).Take(3).Any(s => s == "one"))
{
result = "yellow";
}
else
{
result = "green";
}
}
else
{
result = "blue";
}
}
What would be the value of the "result" variable in the code snippet above?
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content