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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With