Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a collection based on another collection

Tags:

c#

linq

I have a collection of file names with part of the pathname being a specific word. I can order the collection like this :

var files = from f in checkedListBox1.CheckedItems.OfType<string>()
            orderby f.Substring(0,3)
            select f;

But now, I want to sort not by alphabetical order on the pathname part but according to specific order given by another collection.

So let's say the pathname part can be "ATE", "DET" and "RTI". I have another string collection : {"DET", "ATE", "RTI"} that I want to use to sort the filenames so that after sorting, filenames appear with their partname in the order "DET" first, then "ATE", then "RTI". How do I achieve this -> need to use an own comparer ?

like image 348
user957479 Avatar asked Oct 13 '11 06:10

user957479


2 Answers

This should work

var files = from f in checkedListBox1.CheckedItems.OfType<string>()
        orderby anotherCollection.IndexOf(f.Substring(0,3))
        select f;
like image 55
Rikard Pavelic Avatar answered Sep 27 '22 03:09

Rikard Pavelic


Three different variants, depending if you want to use string[], List<string> or a Dictionary<string, int> (good only if you have MANY elements to search for)

string[] collection = new[] { "DET", "ATE", "RTI" };
var files = from f in checkedListBox1.CheckedItems.OfType<string>()
            orderby Array.IndexOf(collection, f.Substring(0, 3))
            select f;

List<string> collection2 = new List<string> { "DET", "ATE", "RTI" };
var files2 = from f in checkedListBox1.CheckedItems.OfType<string>()
            orderby collection2.IndexOf(f.Substring(0, 3))
            select f;

Dictionary<string, int> collection3 = new Dictionary<string, int> 
            { { "DET", 1 }, { "ATE", 2 }, { "RTI", 3 } };

Func<string, int> getIndex = p =>
{
    int res;
    if (collection3.TryGetValue(p, out res))
    {
        return res;
    }
    return -1;
};

var files3 = from f in checkedListBox1.CheckedItems.OfType<string>()
                orderby getIndex(f.Substring(0, 3))
                select f;

I'll add that LINQ doesn't have a "generic" IndexOf method, but you can build one as written here How to get index using LINQ?

like image 44
xanatos Avatar answered Sep 23 '22 03:09

xanatos