根据另一个集合对集合进行排序

6

我有一组文件名,路径名的一部分是特定的单词。我可以按以下方式对该组进行排序:

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

现在,我想按照另一个集合给定的特定顺序进行排序,而不是按路径名部分的字母顺序进行排序。

假设路径名部分可以是“ATE”,“DET”和“RTI”。我有另一个字符串集合:{"DET", "ATE", "RTI"}。我想使用它来对文件名进行排序,以便排序后,文件名按照它们的部件名以“DET”首先,然后是“ATE”,然后是“RTI”的顺序出现。如何实现这个需求呢?需要使用自己的比较器吗?


3个回答

7

这应该可以正常工作

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

只有当anotherCollectionList<string>(或者其他具有IndexOf实例方法的集合类型。例如,数组没有该方法)时才成立。 - xanatos

2

根据您想要使用 string[], List<string> 或者 Dictionary<string, int>(仅适用于需要搜索许多元素的情况)中的哪一个变量,有三种不同的变体。

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;

我要补充的是,LINQ没有“通用的”IndexOf方法,但您可以按照此处所写的构建一个如何使用LINQ获取索引?


0
如果你的问题就像你所说的那样简单,并且只有三个可能的前缀,那么你可以这样做。
var fileNames = checkedListBox1.CheckedItems.OfType<string>();
var files = fileNames.OrderBy(f => 
{
    int value = int.MaxValue;
    switch (f.Substring(0, 3))
    {
        case "DET":
            value = 1;
            break;
        case "ATE":
            value = 2;
            break;
        case "RTI":
            value = 3;
            break;
    }
    return vakue;
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接