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.
This blog is for all Microsoft & .net lovers who may find themselves in need of help or information once in a while. We all have questions and we all need to know more than we know right now. When I come across things that I think may be useful, I post it. When I have something to say that I think is important, which is everything, I post it. All of my C#, ASP.NET, VB, AJAX & programming friends around the world are welcome to the info in my blog - Ramblings Of A Crazy DotNet Woman!
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.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment