LINQ queries on non-generic collections

By | February 21, 2016


LINQ (Language-Integrated Query) is a powerful tool of the .NET Framework. As the name implies, it integrates query capabilities directly into C# (or the .NET language of your choice). This article does not aim to be an introduction to LINQ, but rather how to use LINQ queries on non-generic collections (objects of IEnumerable type). If LINQ is completely unfamiliar to you, then I would recommend finding a tutorial on the web first and come back to this article later.

The standard LINQ query operators are restricted to generic collections (objects of IEnumerable<T> type). By using the IEnumerable extension method Cast<T> provided by LINQ we can easily create an IEnumerable<T>. Once we have an IEnumerable<T> we can perform LINQ queries. It is as simple as that. To solidify our understanding, let’s go through a couple of examples.

Example 1: LINQ query on a StringCollection object

So here we have a StringCollection object and we wish to alphabetically order the contents of the collection. We could write our own routine to reorder the list or we could use the OrderBy extension method provided by LINQ. Lets take the easy route and use the built-in power of LINQ. First, we create a LINQ query capable collection by using Cast<string> to create an IEnumerable<string>. Once we have obtained the generic collection, we order the collection using LINQ as we normally would.

Example 2: LINQ query on a DataTable object

To begin this example, I wrote a small setup script which initializes a DataTable object:

Here is the code which performs LINQ queries over the DataTable:

Here the same approach is used in order to obtain an object which we can perform LINQ queries on. Alternatively, DataTable supports the AsEnumerable method which will return an IEnumerable<DataRow> from a DataTable. I have shown here how Cast<DataRow> can be used instead in order to showcase a more general approach to solving the problem. Again, once we have an IEnumerable<DataRow> we can query the data source using the standard query operators of LINQ.

I hope you found this article helpful. Note that I have exclusively used the method-based query syntax in this article, but query expression syntax could be used instead and everything would be equally valid. I have used the method-based query syntax here out of personal preference and nothing more.

Leave a Reply

Your email address will not be published. Required fields are marked *