[英]Sort my IEnumerable<Group> in alphabetical order
I have a class called Group
containing lots of information retrieved from my database such as as GroupId
a Name
or an Address
. 我有一个名为
Group
的类,其中包含从数据库中检索到的许多信息,例如GroupId
, Name
或Address
。
This is my Index
controller for my Group
page that simply displays all of these information in an ordered manner : 这是我的“
Group
页面的Index
控制器,它仅以有序方式显示所有这些信息:
All the controller does is get the data and passes it to the View. 控制器所做的就是获取数据并将其传递给View。
[Authorize]
public ActionResult Index()
{
return View(_service.List());
}
I pass the data as an IEnumerable<Group>
type, but I wonder: how may I order these information in an alphabetical order depending on Name
? 我将数据作为
IEnumerable<Group>
类型传递,但我想知道:如何根据Name
以字母顺序对这些信息进行排序?
EDIT: Here is my Group
class: 编辑:这是我的
Group
课:
public partial class Group
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Group()
{
this.Companies = new HashSet<Company>();
}
public int GroupId { get; set; }
public string CountryId { get; set; }
public string UpdatedBy { get; set; }
public string CreatedBy { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public bool IsEnabled { get; set; }
public System.DateTime CreatedDate { get; set; }
public System.DateTime UpdatedDate { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Company> Companies { get; set; }
public virtual Country Country { get; set; }
}
My List
method : 我的
List
方法:
public IEnumerable<Group> List()
{
return _repository.List();
}
In the repository: 在存储库中:
public IEnumerable<Group> List()
{
return _entities.Groups.ToList();
}
You can use the OrderBy
method on an IEnumerable
to sort on a specific key in the object. 您可以在
IEnumerable
上使用OrderBy
方法对对象中的特定键进行排序。 See also this MSDN article . 另请参见此MSDN文章 。 Note that
OrderBy
is an extension method. 请注意,
OrderBy
是扩展方法。 So you will need to include the namespace System.Linq
to be able to use it. 因此,您将需要包含名称空间
System.Linq
才能使用它。
Your code would then become 您的代码将变成
return View(_service.List().OrderBy(g => g.Name));
你可以这样做;
return View(_service.List().OrderBy(o=>o.Name).ToList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.