如何将列表中间的项目放在首位?

How to put an item from a middle of a list, on a first place?

我有一个绑定列表:

BindingList<partner> partnerList = _context.partner.Local.ToBindingList();

this._view.PartnerDatasource.DataSource = partnerList;

这是下拉菜单的数据源。我想要的是将特定项目显示为下拉列表中的第一项。我试过这样的事情:

 public  void Swap<T>(IList<T> list, int indexA, int indexB)
        {
            T tmp = list[indexA];
            list[indexA] = list[indexB];
            list[indexB] = tmp;
        }

然后:

 this.Swap(partnerList, 0, partnerList.Count - 1);

这在交换时有效,但它以某种方式完全搞砸了 entity framework,当我尝试使用这些实体(合作伙伴)时,我进一步遇到各种错误...

执行此操作的合适方法是什么?

给他们优先权,然后按它排序:

partnerList.OrderByDesending(x=> x.someProperty == Something); 

或者如果您需要按索引排序:

  partnerList.Select((item ,i) => new { item , neworder = i == index ? 0 : 1})
           .OrderBy(x=> x.neworder).Select(a=> a.item); 

Live Demo

var names = new [] { "Alice", "Bob", "Charlie", "Dave", "Eve" };
var specialName = "Eve";

var sortedNames = names.OrderByDescending(x => x == specialName);
foreach (var name in sortedNames)
    Console.WriteLine(name);

结果:

Eve
Alice
Bob
Charlie
Dave

List 没有实现 Move(Int32 oldIndex, Int32 newIndex) 方法,但 ObservableCollection 实现了。

所以你可以做的是,首先将该列表转换为 ObservableCollection,然后尝试使用 .Move(Int32 oldIndex, Int32 newIndex) 方法。

using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {

        List<Partner> partenrs=new List<Partner>();
        partenrs.Add(new Partner(){Name="A"});
        partenrs.Add(new Partner(){Name="B"});
        partenrs.Add(new Partner(){Name="C"});
        partenrs.Add(new Partner(){Name="D"});
        partenrs.Add(new Partner(){Name="E"});
        partenrs.Add(new Partner(){Name="F"});

        var obser=new ObservableCollection<Partner>(partenrs);

        obser.Move(0,5);
        foreach(var x in obser)
        {
            Console.WriteLine(x.Name);
        }
    }
}

class Partner
{
    public string Name{get;set;}
}