Shani Bhati
Shani Bhati

Reputation: 161

Compare one value to next value in a sorted dictionary

I have a sorted dictionary having names as key and marks as value.

Dictionary<string,int> diM = new Dictionary<string,int>();

Another dictionary to store time taken by respective student.

Dictionary<string,int> diT = new Dictionary<string,int>();

Now if the marks of the two students are same then ranking based on time taken.

var marks = from pair in diM
            orderby pair.Value descending
            select pair;
int j=0;

foreach (KeyValuePair<string, int> pair in marks)
{
    j++;
    Console.WriteLine("{0} {1}",j, pair.Key);
}

Now if one student marks are equal with next student marks (as sorted Dictionary) then student with less time should be output.

Upvotes: 2

Views: 255

Answers (1)

Gilad Green
Gilad Green

Reputation: 37281

First I'd recommend not using dictionaries for this task. Create a class with properties of name, mark and time. Something like:

public class TestResult
{
    public string Name { get; set; }
    public int Grade { get; set; }
    public TimeSpan Time { get; set; }
}

Then hold a list of that type. Whenever you have two separate collections which you somehow need to keep in sync - suspect that there might be a problem in the design.


As for the actual problem, use Linq to join the two dictionaries by the key. Once you did that you can order the results by the mark and then by the time:

var result = from mark in diM
             join time in diT on mark.Key equals time.Key
             orderby mark.Value descending, time.Value
             select new { Name = mark.Key, Grade = mark.Value, Time = time.Value };

Upvotes: 1

Related Questions