Tuesday, December 13, 2011

How To Remove Duplicates And Sort Lists Of Things In C#

This is a quick and dirty simple list of how to remove duplicates from lists of items in C#. It is simple to do, yet a lot of people create monstrous for loops to accomplish deduping and sorting. It isn't and doesn't have to be complex. Here is a quick and easy list of some ways for you to dedupe and sort your lists.

string[] sItems = { "one", "two", "three", "four", "five", "one", "two", "one", "two", "one", "two", "one" };

//counts the number of times a value occurs

var counts = from sItem in sItems

group sItem by sItem into g

select new { Item = g.Key, Count = g.Count() };

//removes duplicates and preserves the original order

var dedupe1 = new HashSet<string>(sItems);

//removes duplicates and preserves the original order

var dedupe2 = sItems.Distinct();

//removes duplicates and reverse the order of elements

var dedupeAndReverse1 = sItems.Distinct().Reverse();

//remove duplicates and sort

var dedupeAndSort = sItems.Distinct().OrderBy(x => x);

There are additional ways to accomplish the same thing, but these are simple, quick and easy to use.

No comments: