三種不同的變化,這取決於如果你想使用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
方法,但你可以建立一個這裏寫的How to get index using LINQ?
(http://stackoverflow.com/questions/3355928/c-sharp-sort-list-based-on-another-list)基於另一個列表C#排序列表]的可能重複 – nawfal