LINQ–notes from the field
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:
- Are not strongly typed (unlike Arrays, Dictionaries, GenericLists which are all strongly typed)
- 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
- ArrayList arrayList = new ArrayList();
- arrayList.Add(new Author { Title = “James Joyce” });
- arrayList.Add(new Author { Title = “Enid Blyton” });
- arrayList.Add(new Author { Title = “James Hilton” });
- var authors_named_James = from author in arrayList.Cast<Author>() where author.FirstName.Contains(“James”)
- 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#
- Use a where clause to specify your filter
- Convert the output to a dictionary using a ToDictionary as shown below:
Finding all the duplicates in a collection
- var duplicates = inputList.GroupBy(i => i).Where(g => g.Count() > 1).Select(g => g.Key);
- foreach (var d in duplicates)
- listBox1.Items.Add("Duplicate Value : " + d);
Leave a Reply