【问题标题】:Sort a collection based on another collection根据另一个集合对集合进行排序
【发布时间】:2011-10-13 06:57:44
【问题描述】:

我有一组文件名,其中部分路径名是特定的单词。我可以这样订购收藏:

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”。我该如何实现 -> 需要使用自己的比较器?

【问题讨论】:

标签: c# linq


【解决方案1】:

这应该可行

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

【讨论】:

  • 仅当anotherColletionList&lt;string&gt; :-)(或其他具有IndexOf 实例方法的集合类型。例如数组没有它)
【解决方案2】:

三种不同的变体,具体取决于您是要使用string[]List&lt;string&gt; 还是Dictionary&lt;string, int&gt;(仅当您有许多要搜索的元素时才适用)

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 方法,但您可以按照此处编写的方法构建一个 How to get index using LINQ?

【讨论】:

    【解决方案3】:

    如果您的问题如您所说的那么简单,并且只有 3 个可能的前缀,您可以这样做。

    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;
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-18
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 2011-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多