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.

5 comments:

  1. Can we use numbers.Contains(0)?

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Cool method, I've always found myself using the IEnumerable LINQ extension method: list.Any(x => x == 0) in those conditions. Two ways of doing the same thing I guess.

    ReplyDelete
  4. Ditto what Kevin said.

    I would hope (and assume) that TrueForAll will Short Circuit the way Any does.

    But since I know Any short circuits, I'll probably just keep using it :)

    ReplyDelete
  5. The other option is to use the All extension method that definitely short circuits

    ReplyDelete