Sprint3rx Sprint3rx - 2 months ago 9
C# Question

How to sort a string array from maximum to minimum amount of that type of elements in c#?

I am sorry for confusing title, how do i make an array of these elements :

string [] anArray = new string[50];
anArray[0] = "New York";
anArray[1] = "London";
anArray[2] = "New York";
anArray[3] = "London";
anArray[4] = "New York";
anArray[5] = "Chicago";


Fall into an array like this :

anArray[0] = "New York";
anArray[1] = "New York";
anArray[2] = "New York";
anArray[3] = "London";
anArray[4] = "London";
anArray[5] = "Chicago";


Where elements are sorted by amount of equal elements are there in the array.
And if for example anArray has an equal amount of elements like :

anArray[0] = "New York";
anArray[1] = "New York";
anArray[2] = "London";
anArray[3] = "London";


How do i make so that a program finds both of these elements and outputs something like:
New York, amount of elements 2
London, amount of elements 2

I'll hope you understand, sorry if it may be confusing, thanks for any help here.

Answer

Just use Linq GroupBy

        string[] anArray = new string[50];
        anArray[0] = "New York";
        anArray[1] = "London";
        anArray[2] = "New York";
        anArray[3] = "London";
        anArray[4] = "New York";
        anArray[5] = "Chicago";

        var GroupedArray = anArray.GroupBy(a => a);
        foreach (var item in GroupedArray)
        {
            Console.WriteLine(item.Key + " -> " + item.Count());
        }
        Console.Read();

        //NewYork -> 3
        //London -> 2
        //Chicago -> 1

On a side note, you initialized the array to hold 50 items which in my example will result in 44 empty string items being taken into account by the groupby clause. If you want to avoid displaying these, replace the groupby line for this one:

var GroupedArray = anArray.GroupBy(a => a).Where(a => !string.IsNullOrEmpty(a.Key));