-5

This is my code and I would like to know how I can put this in an alphabetical list. Thanks!

Process[] proc;

void GetAllProcess()
{
    proc = Process.GetProcesses();
    listBox1.Items.Clear();
    foreach (Process p in proc)
    {
        listBox1.Items.Add(p.ProcessName);
    }
}


private void Form1_Load(object sender, EventArgs e)
{
    GetAllProcess();
}
csharpbd
  • 3,786
  • 4
  • 23
  • 32
austin
  • 11
  • 3
  • 1
    Using the [IEnumerable extension OrderBy](https://msdn.microsoft.com/en-us/library/bb534966(v=vs.110).aspx) – Steve Apr 12 '17 at 21:00

2 Answers2

2

LINQ makes it really easy to work with collections of things and it has an OrderBy option. Once you have them ordered you can again use LINQ to Select the process name of each and then use those names and use Select to insert them into the list.

proc = Process.GetProcesses()
    .OrderBy(p => p.ProcessName)
    .ToArray();
proc.Select(p => p.ProcessName)
    .Select(listBox1.Items.Add);
Blake Thingstad
  • 1,639
  • 2
  • 12
  • 19
1

Please check this, I've modified your function:

void GetAllProcess()
{
    proc = Process.GetProcesses();
    listBox1.Items.Clear();
    foreach (Process p in proc.OrderBy(m=>m.ProcessName))
    {
        listBox1.Items.Add(p.ProcessName);
    }
}
csharpbd
  • 3,786
  • 4
  • 23
  • 32