How to sort a C# dictionary ? How to use SortedDictionary ?

I was struggling to sort a dictionary values based on the number of slashes (/) present in the string.If I am using a normal dictionary we need to write a sorting method and we have to spent a lot of time. Instead we can use the SortedDictionary. Here I am explaining that How to use SortedDictionary in c# based on the number of special character present in the string “How to sort a C# dictionary ? How to use SortedDictionary in c# ?”

namespace WebApplication3
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
search comparer = new search();
SortedDictionary<string, string> sortList = new SortedDictionary<string, string>(comparer);
sortList.Add("/dotnet/stock/.com", "35");
sortList.Add("/dot/net/stock/.com", "25");
sortList.Add("/do/tn/et/st/ock/.com", "29");
sortList.Add("/dotnet/stock.com", "84");
sortList.Add("/dotnetstock.com", "21");
sortList.Add("/d/ot/ne/t/st/o/c/k/.com", "84");
foreach (KeyValuePair<string, string> item in sortList)
{
//print the value
Console.WriteLine("{0}: {1}", item.Key, item.Value);
}
}
}
}

Use this below given code in the search class.

sealed class search: IComparer<string>
{
static int CountSlashes(string str)
{
if (String.IsNullOrEmpty(str))
{
return 0;
}
int count = 0;
for (int i = 0; i < str.Length; i++)
{
if (str[i] == '/')
{
count++;
}
}
return count;
}</code>

<code>public int Compare(string left, string right)
{
int leftCount = CountSlashes(left);
int rightCount = CountSlashes(right);
return rightCount - leftCount;
}
}

Happy Coding!!!:)

Leave a Reply

Your email address will not be published. Required fields are marked *