|
Find Duplicates Using LINQ
How can we find duplicate occurrences of values in a collection? I will demonstrate this here using 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 with this code:
List<City> cities =
new List<City>
{
new City{ Name = "Sydney", Country = "Australia" },
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" },
new City{ Name = "Boston", Country = "USA"}
};
Objective is to find countries which occur more than once in the collection and while I am doing that I would also like to know the number of cities for that country. To do this I can use this query. I am using a foreach loop to output my results.
var query =
from c in cities
group c by c.Country into g
where g.Count() > 1
select new { Country = g.Key, CityCount = g.Count()};
foreach (var item in query)
{
Console.WriteLine("Country {0} has {1} cities", item.Country, item.CityCount);
}
By running the above query I get this output which is correct as there are only two countries in the collection which have more than one city.
![]()
Leave a Reply
6688 views, 2 so far
today |
Get Updates By Email
Popular Post
- LINQ To SQL Tutorial
- LINQ To SQL Join On Multiple Conditions
- Code Sample: Programmatically Download File Using C#
- Free Icons And Images With Visual Studio 2008
- Windows 7 Control Panel In Classic Mode
- Dynamic Sort With LINQ
- Use SqlConnection With LINQ To SQL
- StyleCop Tutorial
- Write To Vista Event Log Using C#
- More Details Emerge On Microsoft Master Certification
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


August 16th, 2008 at 10:39 pm
Good article. Thanks for sharing!