我有一个团队列表。团队以这种方式定义:
public class Team
{
public int ID { get; set; }
public string Name { get; set; }
}
我使用db.Teams.ToList()
查询数据库后返回List<Team>
,我需要使用名称&#34; Total&#34;来推送该列表中的一个团队。到列表的末尾。我怎样才能做到这一点?
答案 0 :(得分:3)
首先,您可以直接在查询中执行此操作:
var list = db.Teams.OrderBy(t => t.Name == "Total" ? 1 : 0).ToList();
但是如果您在填充列表后坚持这样做,那么您可以使用FindIndex
方法查找总项目的索引(如果有的话),并使用{{1将项目移动到最后}和RemoveAt
方法:
Add
在后一种情况下,如果您并不真正关心列表中其他项目的顺序,另一种更有效的方法是简单地将总数与最后一个元素进行交换:
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);
}
答案 1 :(得分:1)
获取列表并将所需的列表移动到最后一个索引。请注意,您不需要订购列表。在这种情况下说你的对象是2
:
List<int> list = new List<int>
{
0,
1,
2,
3,
4
};
// get the object o(n)
int tmp = list.IndexOf(2);
// remove it
list.RemoveAt(2);
// add it to the end of list
list.Add(tmp);
答案 2 :(得分:1)
简答:生成哈希码
请查看@Jon Skeet的答案 - https://stackoverflow.com/a/8094931/6830901
根据我理解的要求更简单:
在第一个循环中对
列表Team.Name != "Total"
进行查找 循环结束后,检查Team.Name == "Total"
放置
Team
的位置无关紧要(想想共享列表)。这取决于我们如何使用查询而不是注入对象的位置