如何按窗口标题</process>对List <process>进行排序

时间:2015-01-03 18:44:48

标签: c# string list sorting process

我相信我会这样做,但我正在考虑如何实现这一点让我感到难过,所以我要求更好的方式

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

3 个答案:

答案 0 :(得分:3)

您可以尝试这样的事情:

var myList = processlist.Where(p=>p.MainWindowTitle.Contains("TX"))
                        .OrderBy(p=>p.MainWindowTitle)
                        .ToList();

答案 1 :(得分:1)

如何使用LINQ&#39; 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.Compare Method

进行排序
Value              Meaning
Less than zero     x is less than y.
Zero               x equals y.
Greater than zero  x is greater than y.

答案 2 :(得分:-1)

嗯,我几乎没有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;
        }
    }
}