我有一个对象数组
MyObjects[] mos = GetMyObjectsArray();
现在我想把 id 为 1085 的元素移到首位,所以我在 LINQ 中编写了以下代码,是否有更优雅的方法来完成这个操作?
mos.Where(c => c.ID == 1085).Take(1).Concat(mos.Where(c => c.ID != 1085)).ToArray();
注意,我希望保存其他项的定位,因此与第一项交换不是解决方案。
这不是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;
}
使用方法:
MyObject[] mos = GetArray();
mos.MoveToFront(c => c.ID == 1085);
void
和抛出异常,为什么还要返回bool
呢? - abatishchev数组并不是你正在尝试的操作的最佳数据结构,它可能需要复制大量的项。对于你所做的事情,你应该使用List。
首先,按如下方式定义一个List扩展方法:
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
}
}
List<int> mos = GetMyObjectsList();
mos.MoveToFront(i => i == 1085);
// 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;
id
的项目位于x
位置。对于这个“空”项目,应该怎么做?折叠还是交换? - abatishchev