CSharp - Use ThenByDescending operator with custom Comparer

Introduction

The names are ordered first by ascending length and then by the ratio of their vowels to consonants, descending.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program/*from ww  w . java 2 s.  c om*/
{
    static void Main(string[] args)
    {
        string[] codeNames = {
           "Python", "Java", "Javascript", "Bash", "C++", "Oracle"};

        MyVowelToConsonantRatioComparer myComp = new MyVowelToConsonantRatioComparer();

        IEnumerable<string> namesByVToCRatio = codeNames
          .OrderBy(n => n.Length)
          .ThenByDescending((s => s), myComp);

        foreach (string item in namesByVToCRatio)
        {
            int vCount = 0;
            int cCount = 0;

            myComp.GetVowelConsonantCount(item, ref vCount, ref cCount);
            double dRatio = (double)vCount / (double)cCount;

            Console.WriteLine(item + " - " + dRatio + " - " + vCount + ":" + cCount);
        }
    }
}
public class MyVowelToConsonantRatioComparer : IComparer<string>
{
    public int Compare(string s1, string s2)
    {
        int vCount1 = 0;
        int cCount1 = 0;
        int vCount2 = 0;
        int cCount2 = 0;

        GetVowelConsonantCount(s1, ref vCount1, ref cCount1);
        GetVowelConsonantCount(s2, ref vCount2, ref cCount2);

        double dRatio1 = (double)vCount1 / (double)cCount1;
        double dRatio2 = (double)vCount2 / (double)cCount2;

        if (dRatio1 < dRatio2)
            return (-1);
        else if (dRatio1 > dRatio2)
            return (1);
        else
            return (0);
    }

    public void GetVowelConsonantCount(string s,
                                       ref int vowelCount,
                                       ref int consonantCount)
    {

        string vowels = "AEIOU";
        vowelCount = 0;
        consonantCount = 0;
        string sUpper = s.ToUpper();

        foreach (char ch in sUpper)
        {
            if (vowels.IndexOf(ch) < 0)
                consonantCount++;
            else
                vowelCount++;
        }

        return;
    }
}

Result

Related Topic