Kiwi
Kiwi

Reputation: 2773

C# Sorting list by another list

I have now 2 lists:

list<string> names;
list<int> numbers;

and I need to sort my names based on the values in numbers. I've been searching, and most use something like x.ID, but i don't really know what that value is. So that didn't work.

Does anyone know, what to do, or can help me out in the ID part?

Upvotes: 3

Views: 6150

Answers (4)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61912

Maybe this is a task for the Zip method. Something like

names.Zip(numbers, (name, number) => new { name, number, })

will "zip" the two sequences into one. From there you can either order the sequence immediately, like

.OrderBy(a => a.number)

or you can instead create a Dictionary<,>, like

.ToDictionary(a => a.number, a => a.name)

But it sounds like what you really want is a SortedDictionary<,>, not a Dictionary<,> which is organized by hash codes. There's no LINQ method for creating a sorted dictionary, but just say

var sorted = new SortedDictionary<int, string>();
foreach (var a in zipResultSequence)
    sorted.Add(a.number, a.name);

Or alternatively, with a SortedDictionary<,>, skip Linq entirely, an go like:

var sorted = new SortedDictionary<int, string>();
for (int idx = 0; idx < numbers.Count; ++idx)  // supposing the two list have same Count
    sorted.Add(numbers[idx], names[idx]);

Upvotes: 3

Kiwi
Kiwi

Reputation: 2773

I fixed it by doing it with an dictionary, this was the result:

dictionary.OrderBy(kv => kv.Value).Reverse().Select(kv => kv.Key).ToList();

Upvotes: 0

Gerald Degeneve
Gerald Degeneve

Reputation: 545

To complement Tims answer, you can also use a custom data structure to associate one name with a number.

public class Person
{
    public int Number { get; set; }   // in this case you could also name it ID
    public string Name { get; set; }
}

Then you would have a List<Person> persons; and you can sort this List by whatever Attribute you like:

List<Person> persons = new List<Person>();
persons.Add(new Person(){Number = 10, Name = "John Doe"});
persons.Add(new Person(){Number = 3, Name = "Max Muster"});

// sort by number
persons = persons.OrderBy(p=>p.Number).ToList();

// alternative sorting method
persons.Sort((a,b) => a.Number-b.Number);

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460018

So i assume that the elements in both lists are related through the index.

names.Select((n, index) => new { Name = n, Index = index })
     .OrderBy(x => numbers.ElementAtOrDefault(x.Index))
     .Select(x => x.Name)
     .ToList();

But i would use another collection type like Dictionary<int,string> instead if both lists are related insomuch.

Upvotes: 8

Related Questions