CSharp - Use ThenBy operator with custom Comparer

Introduction

The following example uses ThenBy operator with custom Comparer.

This example call OrderBy and order by the number of characters in the name.

The names will be ordered ascending by the number of characters, and then within each grouping of names by length, they will be ordered by their vowel to consonant ratio.

The names are first ordered by their length, then by their vowel to consonant ratio.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program//ww w  .j a  va 2 s  . c  o  m
{
    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)
         .ThenBy((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