A Technical Blog article.
View entire blog here.
Often we have to get a count of duplicate items in a list. An easy way to do this is to group the list on the property we want to count, then use LINQ's GroupBy's Count feature. Below is a quick example using an employee list.
private static void Main()
{
List<Employee> empList = new List<Employee>();
empList.Add(new Employee() { ID = 1, FName = "John", Age=23, Sex='M' });
empList.Add(new Employee() { ID = 2, FName = "Mary", Age = 25, Sex = 'F' });
empList.Add(new Employee() { ID = 3, FName = "Amber", Age = 23, Sex = 'M' });
empList.Add(new Employee() { ID = 4, FName = "Kathy", Age=25, Sex='M'});
empList.Add(new Employee() { ID = 5, FName = "Lena", Age=27, Sex='F'});
empList.Add(new Employee() { ID = 6, FName = "John", Age = 28, Sex = 'M' });
empList.Add(new Employee() { ID = 7, FName = "Kathy", Age = 27, Sex = 'F' });
empList.Add(new Employee() { ID = 8, FName = "John", Age = 28, Sex = 'M' });
var dup = empList
.GroupBy(x => new { x.FName })
.Select(group => new { Name = group.Key, Count = group.Count() })
.OrderByDescending(x => x.Count);
foreach (var x in dup)
{
Response.Write(x.Count + " " + x.Name);
}
}
class Employee
{
public int ID { get; set; }
public string FName { get; set; }
public int Age { get; set; }
public char Sex { get; set; }
}


|
| | Msgs 1 to 1 of 1 (Total in Forum: 1) (Refresh) | FirstPrevNext |
|
 |
|
 |
This doesn't actually work. It tells you how many employees have each name, not how many duplicates there are. A count of duplicates would return 2 for John, 1 for Kathy, and 0 where the name is unique. Not worth its own article.
|
|
|
|
 |
|
|
General
News
Question
Answer
Joke
Rant
Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads.