John John
John John

Reputation: 1

how to Order a List<string>

i have the following inside my asp.net mvc web application :-

public ViewResult Details(int id)
{
    var f = repository.AllFindDetails_J(id);
    List<string> ports = new List<string>();
    foreach(var p in f.CS.ITFirewalls)
    {
        ports.Add(p.CSPort);
    }
    foreach (var p2 in f.CS.ITRouters)
    {
        ports.Add(p2.CSPort);
    }
    foreach (var p3 in f.CS.ITSwitches)
    {
        ports.Add(p3.CSPort);
    }
    f.AssignedPorts = ports.Sort();
    return View(f);
}

but i got the following error on the f.AssignedPorts = ports.Sort();:

Cannot implicitly convert type 'void' to 'System.Collections.Generic.List'

Upvotes: 1

Views: 95

Answers (3)

Daniel Mann
Daniel Mann

Reputation: 59055

Sort is a void method -- it sorts the existing list but doesn't return anything.

You can either call Sort before you pass the list into your view, or you can use the OrderBy extension method to order the list and return a new IEnumerable with the sorted contents.

Option #1:

public ViewResult Details(int id)
{
    var f = repository.AllFindDetails_J(id);
    List<string> ports = new List<string>();
    foreach(var p in f.CS.ITFirewalls)
    {
        ports.Add(p.CSPort);
    }
    foreach (var p2 in f.CS.ITRouters)
    {
        ports.Add(p2.CSPort);
    }
    foreach (var p3 in f.CS.ITSwitches)
    {
        ports.Add(p3.CSPort);
    }
    ports.Sort();
    f.AssignedPorts = ports;
    return View(f);
}

Option #2:

public ViewResult Details(int id)
{
    var f = repository.AllFindDetails_J(id);
    List<string> ports = new List<string>();
    foreach(var p in f.CS.ITFirewalls)
    {
        ports.Add(p.CSPort);
    }
    foreach (var p2 in f.CS.ITRouters)
    {
        ports.Add(p2.CSPort);
    }
    foreach (var p3 in f.CS.ITSwitches)
    {
        ports.Add(p3.CSPort);
    }
    //OrderBy requires using System.Linq; 
    f.AssignedPorts = ports.OrderBy(port => port).ToList();
    return View(f);
}

Upvotes: 4

Delta
Delta

Reputation: 851

ports.Sort()
f.AssignedPorts = ports;

this will give you the result that you had.

Upvotes: 0

MDiesel
MDiesel

Reputation: 2667

Try this:

 return View(f.AssignedPorts);

Upvotes: 0

Related Questions