Testing an Expression in a C# List using LINQ ALL
Let's say you have list of items, and you need to quickly find out if all the items in the list match (or don't match) a given criteria. Maybe you want to know if a list of ints are all even, or if all items in the list start with the letter P. I write a lot of game code, so I'm frequently checking if a list of units (soldiers, tanks, trees, whatever) are within a certain distance of a target.
Important Note: All<> does not return a list of the items
in the collection. It returns a bool indicating if all the items in the
list match an expression.
Microsoft Explanation
Determines whether all elements of a sequence satisfy a condition.
public static bool All<TSource>( IEnumerable<TSource> source, Func<TSource, bool> predicate )
In the 2.0 days, we would have to do something like this:
C# 2.0 Example
// build a list and see if all items in it are even
List<int> SampleList = new List<int>() { 1, 1, 2, 3, 5, 8, 13 };
bool IsEven = true;
foreach (int item in SampleList)
{
// if the item is not even, then set the flag and exit the loop
if ((item % 2) != 0)
{
IsEven = false;
break;
}
}
Console.WriteLine(string.Format("Are all numbers even? {0}", IsEven));// Outputs:
// Are all numbers even? False
Now with LINQ, we can write more concise code, like this:
C# 3.0 All<> Example
// build a list and see if all items in it are even
List<int> SampleList = new List<int>() { 1, 1, 2, 3, 5, 8, 13 };
bool AllAreEven = SampleList.All(x => x % 2 == 0);
Console.WriteLine(string.Format("Are all numbers even? {0}", AllAreEven));// Outputs:
// Are all numbers even? False
As you can see, LINQ's All<> returns a bool, true if all items in the list match the expression.
If have questions, comments, or suggestion, please feel to post them in the LINQ Exchange Forum
loading...
loading...
No related posts.
Related posts brought to you by Yet Another Related Posts Plugin.
