To sort a System.Object that is a Dictionary in runtime according to its Key ascendingly and output a list of KeyValuePair, you can follow the steps below:

  1. First, check if the collection is a generic Dictionary by checking its type using reflection.
  2. If it is a generic Dictionary, use the OrderBy method to sort the collection by its keys in ascending order.
  3. Convert the sorted collection to a List using the ToList method.
  4. Finally, iterate over the sorted collection and output the KeyValuePair elements.

Here's the updated code snippet:

System.Object collection = GetDMyObject();
var collectionType = collection.GetType();

if (collectionType.IsGenericType && collectionType.GetGenericTypeDefinition() == typeof(Dictionary<,>))
{
    var dictionaryType = typeof(Dictionary<,>).MakeGenericType(collectionType.GetGenericArguments());
    var orderByMethod = typeof(Enumerable).GetMethods().First(m => m.Name == "OrderBy" && m.GetParameters().Length == 2)
                                            .MakeGenericMethod(dictionaryType.GetGenericArguments());

    var sortedCollection = orderByMethod.Invoke(null, new object[] { collection, collectionType.GetProperty("Keys") });

    var toListMethod = typeof(Enumerable).GetMethod("ToList").MakeGenericMethod(dictionaryType);
    var sortedList = toListMethod.Invoke(null, new object[] { sortedCollection });

    var keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(dictionaryType.GetGenericArguments());
    var keyProperty = keyValuePairType.GetProperty("Key");
    var valueProperty = keyValuePairType.GetProperty("Value");

    foreach (var item in (IEnumerable)sortedList)
    {
        var keyValue = keyProperty.GetValue(item);
        var value = valueProperty.GetValue(item);
        Console.WriteLine($"Key: {keyValue}, Value: {value}");
    }
}

Note: This code assumes that the GetDMyObject() method returns a Dictionary. It uses reflection to dynamically determine the types and invoke the necessary methods

how to sort an SystemObject where its a Dictionary in runtime according to its Key ascendingly and output a list of keyvalue pair you shouldnt use non-generic collectionsfor exampleSystemObject collec

原文地址: http://www.cveoy.top/t/topic/is8L 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录