Learn to program in Visual Basic .NET, the right way

LINQ - Queries

What are Queries?

Simply put, a Query is a request for information from some sort of collection.

Distinct

If you wanted to return all unique items in a collection, then you could use the Distinct Enumerable method.

The following demonstrates how to execute the Distinct method on a collection:

Fiddle: Live Demo

Where

If you wanted to return all items in a collection that meet some condition, like a search query, then you could use the Where clause.

The following demonstrates how to execute a Where clause on a collection:

Fiddle: Live Demo

First

If you wanted to return the first value from a collection then you could use the First or the FirstOrDefault Enumerable methods.

First will return the First value, but will thrown an exception if the collection was empty.

FirstOrDefault will return the First value if the collection is not empty, but if the collection is empty then it will return the default value of the collection.

The following demonstrates how to execute the First and FirstOrDefault Enumerable methods:

Fiddle: Live Demo

Exceptions

If you use First on an empty collection, then a InvalidOperationException will be thrown.

Remarks

There exists more methods that are similar to First and FirstOrDefault, they are:

Single and SingleOrDefault should be used if only one item in the collection meets the query.

Last and LastOrDefault works similarly to First and FirstOrDefault, only it will return the last item in the collection.