根据您想要使用 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获取索引?