[英]how to Order a List<string>
i have the following inside my asp.net mvc web application :- 我在asp.net mvc Web应用程序中包含以下内容:
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();
但是我在f.AssignedPorts = ports.Sort();
上遇到以下错误 : :
Cannot implicitly convert type 'void' to 'System.Collections.Generic.List' 无法将类型“ void”隐式转换为“ System.Collections.Generic.List”
Sort
is a void method -- it sorts the existing list but doesn't return anything. Sort
是一个无效方法-它对现有列表进行排序,但不返回任何内容。
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. 您可以在将列表传递到视图之前调用Sort
,或者可以使用OrderBy
扩展方法对列表进行排序,并返回带有已排序内容的新IEnumerable
。
Option #1: 选项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: 选项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);
}
尝试这个:
return View(f.AssignedPorts);
ports.Sort()
f.AssignedPorts = ports;
this will give you the result that you had. 这将给您带来的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.