Using LINQ on pre-3.0 .NET collections

Often times, you have to deal with regular pre-3.0 collections such as ArrayLists, DataSets etc. These collections:

  1. Are not strongly typed (unlike Arrays, Dictionaries, GenericLists which are all strongly typed)
  2. Do not implementIEnumerable<T> – a pre-requisite for using LINQ to search through them

Does this mean that one cannot use the power of LINQ to query these collections? Fortunately – not!

One simply needs to .Cast the items in the collection to a strongly typed. An example below illustrates taking each element in an ArrayList and Casting it to its underlying type (<Author>). Once we perform this little magic, we can query the collection using our favorite LINQ syntax

Code Snippet
  1. ArrayList arrayList = new ArrayList();
  2.             arrayList.Add(new Author { Title = “James Joyce” });
  3.             arrayList.Add(new Author { Title = “Enid Blyton” });
  4.             arrayList.Add(new Author { Title = “James Hilton” });
  5.  
  6.             var authors_named_James = from author in arrayList.Cast<Author>() where author.FirstName.Contains(“James”)
  7.             select author;

Filtering results from a dictionary (and returning a subset of the dictionary)

Say you have a dictionary that contains a set of data (returned either from a database, a web service or any other means). Say you want to filter our part of the data and only see a filtered set (also in the form of a dictionary). Using LINQ, this is a simple one liner in C#

  1. Use a where clause to specify your filter
  2. Convert the output to a dictionary using a ToDictionary as shown below:

Finding all the duplicates in a collection

Code Snippet
  1. var duplicates = inputList.GroupBy(i => i).Where(g => g.Count() > 1).Select(g => g.Key);
  2.  foreach (var d in duplicates)
  3.      listBox1.Items.Add("Duplicate Value : " + d);

 

Anuj holds professional certifications in Google Cloud, AWS as well as certifications in Docker and App Performance Tools such as New Relic. He specializes in Cloud Security, Data Encryption and Container Technologies.

Initial Consultation

Anuj Varma – who has written posts on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.