Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move item to first in array

Tags:

arrays

c#

linq

I have an array of objects

MyObjects[] mos = GetMyObjectsArray();

Now I want to move some element with id 1085 to first, so I write code like this in LINQ, is there more elegant way to do this?

mos.Where(c => c.ID == 1085).Take(1).Concat(mos.Where(c => c.ID != 1085)).ToArray();

Note, I want to save positioning of other items, so swaping with first item is not a solution

like image 679
Arsen Mkrtchyan Avatar asked Jan 21 '23 17:01

Arsen Mkrtchyan


1 Answers

It's not LINQ, but it's how I'd do it with arrays.

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;
  }

Usage:

MyObject[] mos = GetArray();
mos.MoveToFront(c => c.ID == 1085);
like image 140
Heini Høgnason Avatar answered Jan 30 '23 12:01

Heini Høgnason