Sprint3rx
Sprint3rx

Reputation: 33

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.

Upvotes: 0

Views: 66

Answers (3)

Innat3
Innat3

Reputation: 3576

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));

Upvotes: 1

Cory Carlson
Cory Carlson

Reputation: 186

You can order by the count of each element

var orderedItems = anArray.OrderByDescending(x => x?.Count()).ToArray();

Or you could do it by the length of each string

var orderedItems = anArray.OrderByDescending(x => x?.Length).ToArray();

Both check and return null if the array element is null and returns an ordered array.

Upvotes: 0

Jonesopolis
Jonesopolis

Reputation: 25370

Maybe not the fastest solution, but this is the logic you are after.

var result = anArray.OrderByDescending(o => anArray.Count(c => c == o));

note that you are using an array of size 50, so the first 44 items are going to be null, due to the orderby.

Upvotes: 0

Related Questions