Home / Programming / Blog article: Different Ways Of Retrieving Data From Collections

| RSS

Different Ways Of Retrieving Data From Collections

August 1st, 2008 | No Comments | Posted in Programming

C# as a language has matured over years. We have come a long way from the first version of C# to the current which incorporates LINQ. Here is an example I recently used in a training session. My objective was to show students how we can retrieve items from a collection based on a certain criteria in different ways. The collection in question here is a collection of cities. City class looks like this:

public class City
    {
        public string Name { get; set; }
        public string Country { get; set; }
    }

Cities collection is initialised using this code:

List<City> cities =
                new List<City>
                {
                    new City{ Name = "Sydney", Country = "Australia" },
                    new City{ Name = "New York", Country = "USA" },
                    new City{ Name = "Paris", Country = "France" },
                    new City{ Name = "Milan", Country = "Spain" },
                    new City{ Name = "Melbourne", Country = "Australia" },
                    new City{ Name = "Auckland", Country = "New Zealand" },
                    new City{ Name = "Tokyo", Country = "Japan" },
                    new City{ Name = "New Delhi", Country = "India" },
                    new City{ Name = "Hobart", Country = "Australia" }
                };

The objective is to find all cities in Australia and write their name to console. Here are the different ways it can be done.

Old Fashioned

foreach (City item in cities)
{
  if (item.Country == "Australia")
    Console.WriteLine(item.Name);
}

Using FindAll extension method

foreach (City item in cities.FindAll(IsAustralianCity))
{
  Console.WriteLine(item.Name);
}

private static bool IsAustralianCity(City c)
{
  if (c.Country == "Australia")
    return true;
  else
    return false;
}

using FindAll with anonymous method

foreach (City item in cities.FindAll(
  delegate(City c)
  {
    return c.Country == "Australia";
  }))
{
Console.WriteLine(item.Name);
}

Using a LINQ query

var collection =
  from c in cities
  where c.Country == "Australia"
  select c;

foreach (City item in collection)
{
  Console.WriteLine(item.Name);
}

One liner using Lambda. My absolute favourite.

cities.FindAll(c => c.Country == "Australia")
  .ForEach(c => Console.WriteLine(c.Name));

Quite interesting to see how the language has evolved over time. I guess this is the kind of stuff which keeps us developers going. Good on you Microsoft! Keep it coming.

kick it on DotNetKicks.com

Technorati Tags: ,

Leave a Reply 2403 views, 2 so far today |
Tags: ,

Leave a Reply





Switch to our mobile site