C# Ranking of objects, multiple criteria

前端 未结 5 880
日久生厌
日久生厌 2020-12-05 12:26

I am building a plugin for a LAN party website that I wrote that would allow the use of a Round Robin tournament.

All is going well, but I have some questions about

5条回答
  •  悲哀的现实
    2020-12-05 13:10

    Ranking isn't too hard. Just mishmash OrderBy and Select implementation patterns together and you can have an easy to use Ranking extension method. Like this:

        public static IEnumerable Rank
        (
          this IEnumerable source,
          Func keySelector,
          Func selector
        )
        {
            if (!source.Any())
            {
                yield break;
            }
    
            int itemCount = 0;
            T[] ordered = source.OrderBy(keySelector).ToArray();
            TKey previous = keySelector(ordered[0]);
            int rank = 1;
            foreach (T t in ordered)
            {
                itemCount += 1;
                TKey current = keySelector(t);
                if (!current.Equals(previous))
                {
                    rank = itemCount;
                }
                yield return selector(t, rank);
                previous = current;
            }
        }
    

    Here's some test code

    string[] myNames = new string[]
    { "Bob", "Mark", "John", "Jim", "Lisa", "Dave" };
    //
    var query = myNames.Rank(s => s.Length, (s, r) => new { s, r });
    //
    foreach (var x in query)
    {
      Console.WriteLine("{0} {1}", x.r, x.s);
    }
    

    Which yields these results:

    1 Bob
    1 Jim
    3 Mark
    3 John
    3 Lisa
    3 Dave
    

提交回复
热议问题