Time for action – creating the method
Follow the given steps:
- Create a console application called
Ganagram
(short form for generic anagram). This is a showcase ofSortedList<TKey,TValue>
, solving a real problem. - Add the following method in the
Program.cs
file:public static bool IsAnagram<T>(IEnumerable<T> first, IEnumerable<T> second) { SortedList<T, int> val = new SortedList<<T, int>(); foreach (T element in first) { if (!val.ContainsKey(element)) val.Add(element, 1); else val[element]++; } foreach (T element in second) { if (val.ContainsKey(element)) val[element]--; else return false; } foreach (T element in val.Keys) { if (val[element] != 0) return false; } return true; }
- Call this method from the
Main()
method of the console application as follows: ...
Get .NET 4.0 Generics now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.