Accessing a Dictionary.Keys Key through a numeric index

前端 未结 15 1244
失恋的感觉
失恋的感觉 2020-12-07 13:49

I\'m using a Dictionary where the int is a count of the key.

Now, I need to access the last-inserted Key inside the Dict

15条回答
  •  我在风中等你
    2020-12-07 14:03

    In case you decide to use dangerous code that is subject to breakage, this extension function will fetch a key from a Dictionary according to its internal indexing (which for Mono and .NET currently appears to be in the same order as you get by enumerating the Keys property).

    It is much preferable to use Linq: dict.Keys.ElementAt(i), but that function will iterate O(N); the following is O(1) but with a reflection performance penalty.

    using System;
    using System.Collections.Generic;
    using System.Reflection;
    
    public static class Extensions
    {
        public static TKey KeyByIndex(this Dictionary dict, int idx)
        {
            Type type = typeof(Dictionary);
            FieldInfo info = type.GetField("entries", BindingFlags.NonPublic | BindingFlags.Instance);
            if (info != null)
            {
                // .NET
                Object element = ((Array)info.GetValue(dict)).GetValue(idx);
                return (TKey)element.GetType().GetField("key", BindingFlags.Public | BindingFlags.Instance).GetValue(element);
            }
            // Mono:
            info = type.GetField("keySlots", BindingFlags.NonPublic | BindingFlags.Instance);
            return (TKey)((Array)info.GetValue(dict)).GetValue(idx);
        }
    };
    

提交回复
热议问题