Move item to first array

I have an array of objects

MyObjects[] mos = GetMyObjectsArray(); 

Now I want to transfer some element from id 1085 to the first, so I am writing code like this in LINQ, is there a 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 keep the positioning of other elements, so sharing with the first element is not a solution

+4
source share
3 answers

This is not LINQ, but how to 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; } 

Using:

 MyObject[] mos = GetArray(); mos.MoveToFront(c => c.ID == 1085); 
+5
source
 // input array T[] arr = Get(); // find the item int index = Array.FindIndex(arr, i => i.ID == 1085); if (index == -1) throw new InvalidOperationException(); // get the item T item = arr[index]; // place the item to the first position T[] result = new T[arr.Length]; result[0] = item; // copy items before the index if (index > 0) Array.Copy(arr, 0, result, 1, index); // copy items after the index if (index < arr.Length) Array.Copy(arr, index + 1, result, index + 1, arr.Length - index - 1); return result; 
+2
source

An array is not the best data structure for the operation you are trying to perform, and this may require copying a large number of elements. For what you do, you must use the List.

First, define a list expansion method as follows:

 static class ListExtensions { public static bool MoveToFront<T>(this List<T> list, Predicate<T> match) { int idx = list.FindIndex(match); if (idx != -1) { if (idx != 0) // move only if not already in front { T value = list[idx]; // save matching value list.RemoveAt(idx); // remove it from original location list.Insert(0, value); // insert in front } return true; } return false; // matching value not found } } 

Then you can use the MoveToFront extension method (modified from your example):

 List<int> mos = GetMyObjectsList(); mos.MoveToFront(i => i == 1085); 
+1
source

Source: https://habr.com/ru/post/1335955/


All Articles