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.






About The Author

Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET and regular presenter at conferences and user groups throughout Australia. Being an ASP.NET Insider, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with JavaScript. He also blogs regularly at DotNetCurry.com. Follow him on twitter @malcolmsheridan

5 comments:

Anonymous said...

Can we use numbers.Contains(0)?

Kevin McKelvin said...
This comment has been removed by the author.
Kevin McKelvin said...

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.

Anonymous said...

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 :)

Kevin McKelvin said...

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