将项目移动到数组中的第一个

Ars*_*yan 4 c# linq arrays

我有一个对象数组

MyObjects[] mos = GetMyObjectsArray();
Run Code Online (Sandbox Code Playgroud)

现在我想将一个id为1085的元素移到第一个,所以我在LINQ中编写这样的代码,有更优雅的方法吗?

mos.Where(c => c.ID == 1085).Take(1).Concat(mos.Where(c => c.ID != 1085)).ToArray();
Run Code Online (Sandbox Code Playgroud)

注意,我想保存其他项目的定位,因此与第一项交换不是解决方案

Hei*_*son 5

它不是LINQ,但它是我用数组做的.

public static bool MoveToFront<T>(this T[] mos, Predicate<T> match)
  {
    if (mos.Length == 0)
    {
      return false;
    }
    var idx = Array.FindIndex(mos, match);
    if (idx == -1)
    {
      return false;
    }
    var tmp = mos[idx];
    Array.Copy(mos, 0, mos, 1, idx);
    mos[0] = tmp;
    return true;
  }
Run Code Online (Sandbox Code Playgroud)

用法:

MyObject[] mos = GetArray();
mos.MoveToFront(c => c.ID == 1085);
Run Code Online (Sandbox Code Playgroud)