OrderBy in List on the basis of Dictionary Key-Value

c# dictionary sort by value then by key
c# dictionary orderby key
c# sort dictionary by key linq
c# sorteddictionary sort by key
c# sort dictionary by value descending
dictionary order by value c#
c# sorteddictionary sort by value
c# loop through dictionary orderby key

I have the following List:

List<Student> list = 
[
  {
    "id": 1,
    "name": "Student 1",
    "OtherInformation": {
      "hobby": "Music",
      "Score": 50
    }
  },
  {
    "id": 2,
    "name": "Student 2",
    "OtherInformation": {
      "hobby": "Golf",
      "Score": 70
    }
  },
  {
    "id": 3,
    "name": "Student 3",
    "OtherInformation": {
      "hobby": "Archery",
      "Score": 30
    }
  }
]

Other Information is a Dictionary and I need to OrderBy the complete list using the dictionary Value which will be dynamic i.e. stored in some variable.

var sortKey = "id";
var propertyInfo = typeof(Student).GetProperty(sortKey);
list = list.OrderBy(x => propertyInfo.GetValue(x, null)).ToList();

I'm not able to do the above solution for Dictionary Key-Values such as Score

Student.cs

 public class Student
{
 public string Id {get;set;}
 public string Name {get;set;}
 public IDictionary<string, object> OtherInfomration{get;set;}
}

Help needed.

I think you want to do this:

var sortKey = "OtherInformation";
var propertyInfo = typeof(Student).GetProperty(sortKey);
list = list.OrderBy(x => ((IDictionary<string, object>)propertyInfo.GetValue(x, null))["Score"]).ToList();

Its not entirely clear why you're using reflection however. You could easily just do this:

list = list.OrderBy(x => x.OtherInformation["Score"]).ToList();

C# Sort Dictionary: Keys and Values, Sorting approaches. We can sort a Dictionary with the Keys and Values properties and a List instance. Some approaches are slower than others. Since Input.OrderBy creates a query that returns the items in an ordered order, just assign it to the same dictionary. objectDict = objectDict.OrderBy(obj => obj.Key).ToDictionary(obj => obj.Key, obj => obj.Value);

You can do this:

var sorted = list.OrderBy(x => Convert.ToInt32(x.OtherInformation["Score"]));

Convert.ToInt32 is a bit dodgy as it can throw an exception.

How to sort a Dictionary with C#, How to sort a Dictionary by keys and values using C#. public void SortDictionary() {. // Create a dictionary with string key and Int16 value pair Use orderby to order by values − var val = from ele in d orderby ele.Value ascending select ele; We have set ascending above to sort the dictionary in ascending order.

I made a mini console application using this data:

 class Program
 {
     static void Main(string[] args)
     {
         List<Student> list = new List<Student>()
            {
             new Student() { Id = 1, Name = "Student 1", OtherInformation = new Dictionary<string, string>()
                                         {
                                             { "hobby", "Music" },
                                             { "Score",  "50" }
                                         }
                                     },
             new Student() { Id = 2, Name = "Student 2", OtherInformation = new Dictionary<string, string>()
                                         {
                                             { "hobby", "Golf" },
                                             { "Score",  "70" }
                                         }
                                     },
             new Student() { Id = 3, Name = "Student 3", OtherInformation = new Dictionary<string, string>()
                                         {
                                             { "hobby", "Archery" },
                                             { "Score",  "30" }
                                         }
                                     }
         };

         Console.WriteLine(list.OrderBy(x => x.OtherInformation["Score"]).FirstOrDefault().Name);
         Console.Read();
      }
 }

The result was Student 3 as wanted because he has the lowest score.

EDIT:

Here you can use a pre-defined order statments:

public class OrderByStatment
{
    private string propertyName;

    public OrderByStatment(string propertyName)
    {
        this.propertyName = propertyName;
    }

    public Expression<Func<Student, object>> GetOrderBy()
    {
        switch (this.propertyName)
        {
            case "id": return s => s.Id;
            case "name": return s => s.Name;
            case "score": return s => s.OtherInformation["Score"];
            case "hobby": return s => s.OtherInformation["hobby"];
            default: return s => s.Id;
        }
    }
}

calling it will be then:

Console.WriteLine(list.OrderBy(new OrderByStatment("id").GetOrderBy().Compile()).FirstOrDefault().Name);
Console.WriteLine(list.OrderBy(new OrderByStatment("score").GetOrderBy().Compile()).FirstOrDefault().Name);

You can absolutely make the code better by defining inheritance. Instead of new OrderByStatment("[propertyName]") you can use new IdOrderBy()

Hope that answers your question

Sort a Dictionary by Value in C#, public void SortDictionary(); {; // Create a dictionary with string key and Int16 value pair; Dictionary<string, Int16> AuthorList = new� This program adds keys to a Dictionary and then sorts them by their values. Dictionary instances are not initially sorted. We use the orderby keyword in a query statement.orderby. Example: The dictionary has string keys, and int values. We will reorder the values to go from lowest to highest.

Python : How to Sort a Dictionary by key or Value ? – thispointer.com, So list of tuples (key / value pairs) is sorted by keys. Now we can iterate over this sort list of tuple i.e. all sorted keys value pairs from dictionary� The example code first creates a dictionary and then uses OrderBy method to sort the items. How to Sort a Dictionary by Value using C#. Tune in FREE to the Azure Virtual Conference starting Aug. 7 at 10am ET x

Python, Create a dictionary and display its keys alphabetically. Display both the keys and values sorted in alphabetical order by the key. Python - Sort list of Single Item dictionaries according to custom ordering � Python - Convert� OrderBy (v => v. Value); or var sortedKeys = from pair in dictName orderby pair. Value ascending select pair; its also depend on what kind of values you are storing, is it single (like string, int) or multiple (like List, Array, user defined class), if single you can make list of it then apply sort.

Ways to sort list of dictionaries by values in Python, Dictionary in Python is widely used in many applications ranging from Having a knowledge to sort dictionaries according to its values can prove useful in such cases. print "The list printed sorting by age and name: ". Because IOrderedEnumerable<TElement> inherits from IEnumerable<T>, you can call OrderBy or OrderByDescending on the results of a call to OrderBy, OrderByDescending, ThenBy or ThenByDescending. Doing this introduces a new primary ordering that ignores the previously established ordering.

Comments
  • Why did you mix List<Student> list with plain JSON?
  • Please post your dictionary.
  • @PavelAnikhouski I haven't mixed, just wanna provide a view of my list
  • @canton7 The dictionary is already there in the list in the form of "OtherInformation".
  • Is it even compiled?
  • list = list.OrderBy(x => propertyInfo.GetValue(x, null)["Score"]).ToList(); gives out error: "Cannot apply indexing with [] to an expression of type 'object'"
  • see my edit. Forgot the GetValue function just returns object so it needs to be cast
  • could you explain why you are using reflection? Surely you deserialize your json into a list of student classes and then you can just use the second version above
  • The column name and sorting order is requested as: "id asc" or "OtherInformation.score". It is not known to the code that which column can be requested
  • ah i see, it does make sense in that case
  • Please read above, the situation is required for cases where Dictionary Name and Key Name is not known
  • I personally don't suggest to work with reflection (GetProperty) due to performance issues