列表按字母顺序排序

发布于 2024-07-07 05:06:24 字数 250 浏览 4 评论 0原文

我在 Framework 3.5 上使用 C#。 我希望快速对通用 List 进行排序。 对于此示例,假设我有一个 Person 类型的列表,其属性为姓氏。 我如何使用 lambda 表达式对此列表进行排序?

List<Person> people = PopulateList();
people.OrderBy(???? => ?????)

I'm using C# on Framework 3.5. I'm looking to quickly sort a Generic List<T>. For the sake of this example, let's say I have a List of a Person type with a property of lastname. How would I sort this List using a lambda expression?

List<Person> people = PopulateList();
people.OrderBy(???? => ?????)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

指尖上得阳光 2024-07-14 05:06:24

如果您的意思是就地排序(即列表已更新):

people.Sort((x, y) => string.Compare(x.LastName, y.LastName));

如果您的意思是新列表:

var newList = people.OrderBy(x=>x.LastName).ToList(); // ToList optional

If you mean an in-place sort (i.e. the list is updated):

people.Sort((x, y) => string.Compare(x.LastName, y.LastName));

If you mean a new list:

var newList = people.OrderBy(x=>x.LastName).ToList(); // ToList optional
甜心 2024-07-14 05:06:24

您是否需要对列表进行就地排序,或者只是列表内容的有序序列? 后者更容易:

var peopleInOrder = people.OrderBy(person => person.LastName);

要就地排序,您需要一个 IComparerComparison。 为此,您可能希望考虑 MiscUtil 中的 ProjectionComparer

(我知道我一直在提起 MiscUtil - 它只是一直相关......)

Do you need the list to be sorted in place, or just an ordered sequence of the contents of the list? The latter is easier:

var peopleInOrder = people.OrderBy(person => person.LastName);

To sort in place, you'd need an IComparer<Person> or a Comparison<Person>. For that, you may wish to consider ProjectionComparer in MiscUtil.

(I know I keep bringing MiscUtil up - it just keeps being relevant...)

忆沫 2024-07-14 05:06:24
people.OrderBy(person => person.lastname).ToList();
people.OrderBy(person => person.lastname).ToList();
寻找我们的幸福 2024-07-14 05:06:24

您可以使用 linq :) 使用:

System.linq;
var newList = people.OrderBy(x=>x.Name).ToList();

you can use linq :) using :

System.linq;
var newList = people.OrderBy(x=>x.Name).ToList();
雨落星ぅ辰 2024-07-14 05:06:24
private void SortGridGenerico< T >(
          ref List< T > lista       
    , SortDirection sort
    , string propriedadeAOrdenar)
{

    if (!string.IsNullOrEmpty(propriedadeAOrdenar)
    && lista != null
    && lista.Count > 0)
    {

        Type t = lista[0].GetType();

        if (sort == SortDirection.Ascending)
        {

            lista = lista.OrderBy(
                a => t.InvokeMember(
                    propriedadeAOrdenar
                    , System.Reflection.BindingFlags.GetProperty
                    , null
                    , a
                    , null
                )
            ).ToList();
        }
        else
        {
            lista = lista.OrderByDescending(
                a => t.InvokeMember(
                    propriedadeAOrdenar
                    , System.Reflection.BindingFlags.GetProperty
                    , null
                    , a
                    , null
                )
            ).ToList();
        }
    }
}
private void SortGridGenerico< T >(
          ref List< T > lista       
    , SortDirection sort
    , string propriedadeAOrdenar)
{

    if (!string.IsNullOrEmpty(propriedadeAOrdenar)
    && lista != null
    && lista.Count > 0)
    {

        Type t = lista[0].GetType();

        if (sort == SortDirection.Ascending)
        {

            lista = lista.OrderBy(
                a => t.InvokeMember(
                    propriedadeAOrdenar
                    , System.Reflection.BindingFlags.GetProperty
                    , null
                    , a
                    , null
                )
            ).ToList();
        }
        else
        {
            lista = lista.OrderByDescending(
                a => t.InvokeMember(
                    propriedadeAOrdenar
                    , System.Reflection.BindingFlags.GetProperty
                    , null
                    , a
                    , null
                )
            ).ToList();
        }
    }
}
梦罢 2024-07-14 05:06:24

对我来说这个有用的虚拟指南 - 在通用列表中排序 - 有效。
它可以帮助您理解 4 种方法(重载)来完成这项工作,并提供非常完整和清晰的解释和简单的示例

  • List.Sort ()
  • List.Sort (Generic Comparison)
  • List.Sort (Generic IComparer)
  • List.Sort (Int32, Int32,通用 IComparer)

for me this useful dummy guide - Sorting in Generic List - worked.
it helps you to understand 4 ways(overloads) to do this job with very complete and clear explanations and simple examples

  • List.Sort ()
  • List.Sort (Generic Comparison)
  • List.Sort (Generic IComparer)
  • List.Sort (Int32, Int32, Generic IComparer)
最后的乘客 2024-07-14 05:06:24

您可以使用以下代码片段:

var New1 = EmpList.OrderBy(z => z.Age).ToList();

其中 New1List

EmpListList 的变量。

zEmployee 类型的变量。

You can use this code snippet:

var New1 = EmpList.OrderBy(z => z.Age).ToList();

where New1 is a List<Employee>.

EmpList is variable of a List<Employee>.

z is a variable of Employee type.

谜兔 2024-07-14 05:06:24

您还可以使用

model.People = model.People.OrderBy(x => x.Name).ToList();

You can also use

model.People = model.People.OrderBy(x => x.Name).ToList();
陌生 2024-07-14 05:06:24

这是一个通用的排序器。 用下面的开关调用。

dvm.PagePermissions 是我的 ViewModel 类型的属性
本例中的列表 T 是一个名为 page_permission 的 EF6 模型类。

dvm.UserNameSortDir 是视图模型上的一个字符串属性,用于保存下一个排序方向。 视图中实际使用的那个。

switch (sortColumn)
{
    case "user_name":
        dvm.PagePermissions = Sort(dvm.PagePermissions, p => p.user_name, ref sortDir);
        dvm.UserNameSortDir = sortDir;
        break;
    case "role_name":
        dvm.PagePermissions = Sort(dvm.PagePermissions, p => p.role_name, ref sortDir);
        dvm.RoleNameSortDir = sortDir;
        break;
    case "page_name":
        dvm.PagePermissions = Sort(dvm.PagePermissions, p => p.page_name, ref sortDir);
        dvm.PageNameSortDir = sortDir;
        break;
}                 


public List<T> Sort<T,TKey>(List<T> list, Func<T, TKey> sorter, ref string direction)
    {
        if (direction == "asc")
        {
            list = list.OrderBy(sorter).ToList();
            direction = "desc";
        }
        else
        {
            list = list.OrderByDescending(sorter).ToList();
            direction = "asc";
        }
        return list;
    }

This is a generic sorter. Called with the switch below.

dvm.PagePermissions is a property on my ViewModel of type
List T in this case T is a EF6 model class called page_permission.

dvm.UserNameSortDir is a string property on the viewmodel that holds the next sort direction. The one that is actaully used in the view.

switch (sortColumn)
{
    case "user_name":
        dvm.PagePermissions = Sort(dvm.PagePermissions, p => p.user_name, ref sortDir);
        dvm.UserNameSortDir = sortDir;
        break;
    case "role_name":
        dvm.PagePermissions = Sort(dvm.PagePermissions, p => p.role_name, ref sortDir);
        dvm.RoleNameSortDir = sortDir;
        break;
    case "page_name":
        dvm.PagePermissions = Sort(dvm.PagePermissions, p => p.page_name, ref sortDir);
        dvm.PageNameSortDir = sortDir;
        break;
}                 


public List<T> Sort<T,TKey>(List<T> list, Func<T, TKey> sorter, ref string direction)
    {
        if (direction == "asc")
        {
            list = list.OrderBy(sorter).ToList();
            direction = "desc";
        }
        else
        {
            list = list.OrderByDescending(sorter).ToList();
            direction = "asc";
        }
        return list;
    }
飘逸的'云 2024-07-14 05:06:24

在 .NET 7 预览版中,您可以使用简化的排序System.Linq 的 a>。 它还具有一些性能改进。

var sorted = people.Order();

另外,请注意,Sort 方法在大多数情况下具有更好的性能,因为您无需分配新列表。

In .NET 7 preview you can use the simplified ordering of System.Linq. It also has some performance improvements.

var sorted = people.Order();

Also, be aware that the Sort method has a better performance in most cases because you don't allocate a new list.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文