aliattar
aliattar

Reputation: 21

Sort a List<string> according to another List<int>

I have two Lists:

student = new list<string>() {"Bob" , "Alice" , "Roger" , "Oscar"};

Marks = new list<int>() {80,95,70,85};

I want sort Student by Marks in fastest style and the expected output must be:

Student = {"Alice","Oscar","Bob","Roger"}

Is there any command under list methods same as list.sort or list.orderby to achieve the goal?

Upvotes: 2

Views: 992

Answers (3)

John Jesus
John Jesus

Reputation: 2404

Pair the name and score using the Tuple class.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<Tuple<string, int>> list = new List<Tuple<string, int>>();
        list.Add(new Tuple<string, int>("Bob",80 ));
        list.Add(new Tuple<string, int>("Alice", 95));
        list.Add(new Tuple<string, int>("Roger", 70));
        list.Add(new Tuple<string, int>("Oscar", 85));

        // Use Sort method with Comparison delegate.
        // ... Has two parameters; return comparison of Item2 on each.
        list.Sort((a, b) => a.Item2.CompareTo(b.Item2));

        foreach (var element in list)
        {
            Console.WriteLine(element);
        }
    }
}

Upvotes: 1

aquaraga
aquaraga

Reputation: 4168

You could use Zip function together with Tuples.

student.Zip(Marks, (s, n) => new Tuple<string, int>(s,n)).Sort(t => t.Item2).Select(t => t.Item1);

Upvotes: 2

Matt Houser
Matt Houser

Reputation: 36043

Don't use 2 arrays.

Your best approach is to use a class to store pairs of data.

public class Student
{
  public string Name { get; set; }
  public int Mark { get; set; }
}

Once you have an array of Student objects

List<Student> students = new List<Student>();
students.Add(...);

Then you can sort the names together with the marks

var sortedStudents = students.OrderBy(s => s.Mark).ToList();

Upvotes: 10

Related Questions