Menus

Tuesday, December 4, 2012

Using TrueForAll with Generic Lists

If you work with generic lists, you’ll know sometimes you need to check the values in the list to see if they match certain criteria. A method I don’t see used allot is TrueForAll. This is part of the List<T> class. It determines whether every element in the List<(Of <(T>)>) matches the conditions defined by the specified predicate. For example you have the following code:
C#
var numbers = new List<int>() { 4, 6, 7, 8, 34, 33, 11};
VB.NET (Option Infer On)
Dim numbers = New List(Of Integer) (New Integer() {4, 6, 7, 8, 34, 33, 11})
If you needed to check if you had any zeros values, you could write a foreach statement like this:
C#
bool isTrue = false;
foreach (var i in numbers)
{
if (i == 0)
{
          isTrue = true;
}
}
VB.NET
Dim isTrue As Boolean = False
For Each i In numbers
If i = 0 Then
          isTrue = True
End If
Next i
There’s nothing wrong with that code, but by using the TrueForAll method, you can roll that up into one line of code:
C#
var numbers = new List<int>() { 4, 6, 7, 8, 34, 33, 11};
var isTrue = numbers.TrueForAll(o => o > 0);
VB.NET
Dim numbers = New List(Of Integer) (New Integer() {4, 6, 7, 8, 34, 33, 11})
Dim isTrue = numbers.TrueForAll(Function(o) o > 0)
That makes your code more readable than the previous example, and it also looks more elegant in my opinion.

No comments:

Post a Comment