我有一个窗口列表,但它不是我想要的顺序。我可以从标题中将窗口变成字符串 - 它们被放入窗口列表中。我想按照Estimate 1st,Control Center 2nd和Login 3rd的特定顺序对此列表进行排序。这是我想要的顺序。我知道如何去做它,但我想在它进入foreach循环之前对它进行排序。
private void CloseMainWindows(IEnumerable<Window> Windows)
{
var winList = Windows.ToList();
winList.Sort()//This is where I want to sort the list.
foreach (Window window in winList)
{
if (window.Title.Contains("Estimate"))
{
Estimate.closeEstimateWindow();
}
if (window.Title.Contains("Control Center"))
{
ContorlCenter.CloseContorlCenter();
}
if (window.Title.Contains("Login"))
{
login.ClickCanel();
}
}
}
答案 0 :(得分:3)
一种方法是拥有查找功能:
int GetTitleIndex(string s)
{
if (s.Contains("Estimate")) return 0;
if (s.Contains("Control Center")) return 1;
if (s.Contains("Login")) return 2;
}
然后,要进行排序,请查找索引:
winList.Sort((x, y) => GetTitleIndex(x).CompareTo(GetTitleIndex(y)));
或者,您可以使用LINQ&#39; OrderBy
:
var winList = Windows.OrderBy(GetTitleIndex).ToList();
事实上,在你的情况下,你甚至不需要中间名单:
foreach (var window in Windows.OrderBy(GetTitleIndex))
{
...
}
答案 1 :(得分:0)
您可以这样做:
List<Type> data = new List<Type>();
data.Sort(new Comparison<Type>(Compare));
private static int Compare(Type x, Type y)
{
//you can compare them like so :
//I'll show you an example just for the sake of illustrating how :
if(x.Name.ToString().Length > y.Name.ToString().Length) return 1;
else return -1;
//the logic for the comparison is up to you.
//compare the 2 elements.
}