satish kumar V
satish kumar V

Reputation: 1755

How do I sort the dynamic list in c#

function void sortDynamicData(typeOfClass,SortKey)
{
List<dynamic> results = null; //results might be of any type it may contain students data or books data or professors data, hence I took as dynamic
results = services.GetMyresults(typeOfClass); //returns list of dynamic objects

results = results.OrderBy(SortKey).ToList();
 ...
 ...
 ...

}

my question is I want to sort the results based on sortKey Any help would be greatly appreciable.

Upvotes: 6

Views: 19687

Answers (3)

Mohamad Chami
Mohamad Chami

Reputation: 1234

1- order by one field

var personList = new List<dynamic>
{
    new { FullName = "Person 2" },
    new { FullName = "People 2" },
    new { FullName = "People 1" },
    new { FullName = "Person 1" }
};
    
List<dynamic> sortedPersonList = personList.AsEnumerable().OrderBy(x => x.FullName).ToList();

result

{ FullName = "People 1" }
{ FullName = "People 2" }
{ FullName = "Person 1" }
{ FullName = "Person 2" }

2- order by multiple fields

var personList = new List<dynamic>
{
     new { FirstName = "Person", LastName = "2" },
     new { FirstName = "People", LastName = "2" },
     new { FirstName = "People", LastName = "1" },
     new { FirstName = "Person", LastName = "1" }
};
        
List<dynamic> sortedPersonList = personList.AsEnumerable().OrderBy(x => x.FirstName).ThenBy(x => x.LastName).ToList();

result

{ FirstName = "People", LastName = "1" }
{ FirstName = "People", LastName = "2" }
{ FirstName = "Person", LastName = "1" }
{ FirstName = "Person", LastName = "2" }

Upvotes: 1

Phuong Nguyen
Phuong Nguyen

Reputation: 3080

If possible, I think it's better and easier to work with if your data is List of T instead of List of dynamic

In case you cannot change your input data to List:

public List<dynamic> Sort<T>(List<dynamic> input, string property)
{
    var type = typeof(T);   
    var sortProperty = type.GetProperty(property);
    return input.OrderBy(p => sortProperty.GetValue(p, null)).ToList();
}

Usage: you need to provide the type of data in the list, e.g. sort List by Name property in which dynamic is of Person type

var result = Sort<Person>(people, "Name");

================

Update:

In case you cannot provide the type of data, you can try this Sort()

public List<dynamic> Sort(List<dynamic> input, string property)
{   
    return input.OrderBy(p => p.GetType()
                               .GetProperty(property)
                               .GetValue(p, null)).ToList();
}

Usage:

var people = new List<dynamic>
{
    new Person { Name = "Person 5" },
    new Person { Name = "Person 2" },
    new Person { Name = "Person 9" },
    new Person { Name = "Person 1" }
};  

var result = Sort(people, "Name");

Upvotes: 19

agentpx
agentpx

Reputation: 1081

var final = results.AsEnumerable().OrderBy(x => x[0])

Upvotes: 2

Related Questions