Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# : How to sort a list of object based on a list of string

I'm having two list like

 List<String> l_lstNames = new List<String> { "A1", "A3", "A2", "A4", "A0" };

List<Test> l_lstStudents = new List<Test> 
                            { new Test { Age = 20, Name = "A0" }, 
                              new Test { Age = 21, Name = "A1" }, 
                              new Test { Age = 22, Name = "A2" }, 
                              new Test { Age = 23, Name = "A3" }, 
                              new Test { Age = 24, Name = "A4" }, 
                            };

Where Test is class like

 public class Test
    {
        public String Name;
        public Int32 Age;
    }

I need to sort the items in the l_lstStudents based on the l_lstNames. So the sorted list will be like,

List<Test> l_lstStudents = new List<Test> 
                        {  new Test { Age = 21, Name = "A1" }, 
                           new Test { Age = 23, Name = "A3" }, 
                           new Test { Age = 22, Name = "A2" }, 
                           new Test { Age = 24, Name = "A4" }, 
                           new Test { Age = 20, Name = "A0" }, 
                        };

Now i'm using for to do this.

Like

  1. Create a new list of Test objects.

  2. Iterate the loop for l_lstNames and fetch the Test object from l_lstStudent and add the same to the newly created list. Finally assign the new list to l_lstStudent

Please help me to do this in a simple way ( Linq or Lambda)

like image 873
Thorin Oakenshield Avatar asked Mar 09 '12 11:03

Thorin Oakenshield


3 Answers

Try this:

l_lstStudents = l_lstStudents.OrderBy(s => l_lstNames.IndexOf(s.Name)).ToList()

I think that expresses the intention quite clearly.

like image 169
Botz3000 Avatar answered Oct 16 '22 01:10

Botz3000


How about

var studentLookup = l_lstStudents.ToDictionary(s => s.Name, s => s);
return l_lstNames.Select(n => studentLookup[n]);
like image 41
Rawling Avatar answered Oct 16 '22 00:10

Rawling


Try this. Putting it in a dictionary may save some look up time:

int i = 0;
Dictionary<string, int> ordinalValues = l_lstNames.ToDictionary(name => name, name => i++);
var sortedStudents = l_lstStudents.OrderBy( a => ordinalValues[a.Name]).ToList();
like image 42
Tung Avatar answered Oct 16 '22 00:10

Tung