Sort System.Object Dictionary by Key Ascendingly in C# (Runtime)
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:\n\n1. First, check if the collection is a generic Dictionary by checking its type using reflection.\n2. If it is a generic Dictionary, use the OrderBy method to sort the collection by its keys in ascending order.\n3. Convert the sorted collection to a List using the ToList method.\n4. Finally, iterate over the sorted collection and output the KeyValuePair elements.\n\nHere's the updated code snippet:\n\ncsharp\nSystem.Object collection = GetDMyObject();\nvar collectionType = collection.GetType();\n\nif (collectionType.IsGenericType && collectionType.GetGenericTypeDefinition() == typeof(Dictionary<,>))\n{\n var dictionaryType = typeof(Dictionary<,>).MakeGenericType(collectionType.GetGenericArguments());\n var orderByMethod = typeof(Enumerable).GetMethods().First(m => m.Name == "OrderBy" && m.GetParameters().Length == 2)\n .MakeGenericMethod(dictionaryType.GetGenericArguments());\n\n var sortedCollection = orderByMethod.Invoke(null, new object[] { collection, collectionType.GetProperty("Keys") });\n\n var toListMethod = typeof(Enumerable).GetMethod("ToList").MakeGenericMethod(dictionaryType);\n var sortedList = toListMethod.Invoke(null, new object[] { sortedCollection });\n\n var keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(dictionaryType.GetGenericArguments());\n var keyProperty = keyValuePairType.GetProperty("Key");\n var valueProperty = keyValuePairType.GetProperty("Value");\n\n foreach (var item in (IEnumerable)sortedList)\n {\n var keyValue = keyProperty.GetValue(item);\n var value = valueProperty.GetValue(item);\n Console.WriteLine($"Key: {keyValue}, Value: {value}");\n }\n}\n\n\nNote: This code assumes that the GetDMyObject() method returns a Dictionary. It uses reflection to dynamically determine the types and invoke the necessary methods.
原文地址: https://www.cveoy.top/t/topic/qaH8 著作权归作者所有。请勿转载和采集!