gpt4 book ai didi

c# - 使用 LINQ 将项目移动到列表顶部

转载 作者:IT王子 更新时间:2023-10-29 03:39:34 24 4
gpt4 key购买 nike

有没有办法使用 LINQ 将 id=10 的项目移动为列表中的第一项?

Item A - id =5Item B - id = 10Item C - id =12Item D - id =1

In this case how can I elegantly move Item C to the top of my List<T> collection?

This is the best I have right now:

var allCountries = repository.GetCountries();
var topitem = allCountries.Single(x => x.id == 592);
var finalList = new List<Country>();
finalList.Add(topitem);
finalList = finalList.Concat(allCountries.Where(x=> x.id != 592)).ToList();

最佳答案

除了已知的顶级商品之外,您还想根据什么来订购?如果你不在乎,你可以这样做:

var query = allCountries.OrderBy(x => x.id != 592).ToList();

基本上,“假”在“真”之前......

诚然,我不知道这在 LINQ to SQL 等中做了什么。您可能需要阻止它在数据库中进行排序:

var query = allCountries.AsEnumerable()
.OrderBy(x => x.id != 592)
.ToList();

关于c# - 使用 LINQ 将项目移动到列表顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1668451/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com