|
Different Ways Of Retrieving Data From Collections
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.
Leave a Reply
Get Updates By Email
Popular Post
Tag Cloud
Code Snippets
- Get Current Windows User In C#
- Get Width And Height Of Image In C#
- Get Windows Registry Size With WMI And C#
- Reverse Array Elements Using C#
- Convert Hexadecimal To Number In C#
- Get Free Disk Space Using T-SQL
- SQL Server 2008 – Get All Indexes In A Database
- Get Name Of Current Executing Assembly In C#
- Get CD Or DVD Drive Information Using WMI And C#
- Get Last Row From Table Using LINQ To SQL

