如何按窗口标题对列表<进程>进行排序
本文关键字:排序 进程 何按 窗口标题 列表 | 更新日期: 2023-09-27 18:35:59
我相信我会这样做,但是我思考如何实现这一目标的方式让我很难过,所以我要求更好的方法
List<Process> myList = new List<Process>();
Process[] processlist = Process.GetProcesses(); // Load all existing processes
// Pin existing sessions to the application
foreach (Process p in processlist)
{
if (p.MainWindowTitle.Contains("TX")) // schema is like TX1 => TX10, but this loop is not sorted at all
{
myList.Add(p); // Unsorted list when looking by MainWindowTitle property
}
}
对不起,也没有预先提出我想要实现哪种排序的问题
[0] TX1
[1] TX2
...
[5] TX6
等。
你可以尝试这样的事情:
var myList = processlist.Where(p=>p.MainWindowTitle.Contains("TX"))
.OrderBy(p=>p.MainWindowTitle)
.ToList();
如何使用 LINQ 的OrderBy
和简单的自定义比较器。在这种情况下,这可能就足够了。根据您提供给我们的信息,它应该适合您。
class Program
{
static void Main(string[] args)
{
var names = new string[] { "TX2", "TX12", "TX10", "TX3", "TX0" };
var result = names.OrderBy(x => x, new WindowNameComparer()).ToList();
// = TX0, TX2, TX3, TX10, TX13
}
}
public class WindowNameComparer : IComparer<string>
{
public int Compare(string x, string y)
{
string pattern = @"TX('d+)";
var xNo = int.Parse(Regex.Match(x, pattern).Groups[1].Value);
var yNo = int.Parse(Regex.Match(y, pattern).Groups[1].Value);
return xNo - yNo;
}
}
WindowNameComparer
读取(解析)附加到TX
的数字,并计算差异,然后根据IComparer的此表用于排序。
Value Meaning
Less than zero x is less than y.
Zero x equals y.
Greater than zero x is greater than y.
好吧,我几乎没有linq就做了这个,但我想这有点矫枉过正
Process temp = null;
for (int i = 0; i < Games.Count; i++)
{
for (int sort = 0; sort < Games.Count - 1; sort++)
{
string title1 = Games[sort].MainWindowTitle;
string title2 = Games[sort+1].MainWindowTitle;
int titleAsIntSum1 = title1.Sum(b => b); // This will work in this case
int titleAsIntSum2 = title2.Sum(b => b);
if (titleAsIntSum1 > titleAsIntSum2)
{
temp = Games[sort + 1];
Games[sort + 1] = Games[sort];
Games[sort] = temp;
}
}
}