c# - 如何将现有项目推到列表末尾?

标签 c# asp.net list sorting

<分区>

我有一个团队列表。团队是这样定义的:

public class Team
{
    public int ID { get; set; }

    public string Name { get; set; }
}

在我使用 db.Teams.ToList() 查询数据库之后,它返回一个 List<Team> ,我需要将该列表中名称为“Total”的团队之一推到列表的末尾。我怎样才能做到这一点?

最佳答案

首先,您可以直接在查询中执行此操作:

var list = db.Teams.OrderBy(t => t.Name == "Total" ? 1 : 0).ToList();

但如果您坚持在列表填充后执行此操作,那么您可以使用 FindIndex方法找到总项目的索引(如果有的话),然后使用 RemoveAtAdd 方法将项目移动到末尾:

var list = db.Teams.ToList();
int index = list.FindIndex(t => t.Name == "Total");
if (index >= 0 && index != list.Count - 1)
{
    var total = list[index];
    list.RemoveAt(index);
    list.Add(total);
}

在后一种情况下,如果您真的不关心列表中其他项目的顺序,另一种更有效的方法是简单地将总数与最后一个元素交换:

if (index >= 0 && index != list.Count - 1)
{
    var total = list[index];
    list[index] = list[list.Count - 1];
    list[list.Count - 1] = total;
}

关于c# - 如何将现有项目推到列表末尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39550752/

相关文章:

c# - 如何检查 secret 是否在 Azure Key Vault 中

c# - 使用 EmptyDataTemplate 时如何删除 ASP.NET GridView 中的空行?

c - 错误: incompatible type for argument

c# - 关于 C# 中泛型与 Java 比较的问题

c# - 调整数组大小以丢失空值

c# - 从 DataTemplate 绑定(bind) ZIndex

asp.net - Mod Rewrite MS Hosting 通过显示短 URL 隐藏长烦人的 URL?

asp.net - 正在寻找一个好的 jQuery 数据网格插件

python - 尝试将内部和外部元组转换为内部和外部列表

list - 在 R 中解压省略号的参数列表