Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 10. Collections > Count the Number of Times an Item Appears - Pg. 168

168 CHAPTER 10 Collections p.Next = tail; //reset the end tail = p; p = n; } //the new head is where the tail is head = tail; } Get the Unique Elements from a Collection Scenario/Problem: Given a collection of objects, you need to generate a new collection containing just one copy of each item. Solution: To generate a collection without the duplicate items, you need to track which items are found in the collection, and only add them to the new collection if they haven't been seen before, as in this example: private static ICollection<T> GetUniques<T>(ICollection<T> list) { //use a dictionary to track whether you've seen an element yet Dictionary<T, bool> found = new Dictionary<T, bool>(); List<T> uniques = new List<T>(); //this algorithm will preserve the original order foreach (T val in list) { if (!found.ContainsKey(val)) { found[val] = true; uniques.Add(val); } } return uniques; } Count the Number of Times an Item Appears Scenario/Problem: You need to count the number of times each element appears in a collection. Solution: This is quite similar to the previous section.