几天来我一直在尝试这样做,但我所能做的就是对完整列表进行排序,但无法从特定索引进行排序。
比方说我有以下列表
List<byte[]> byteArrayList = new list<byte[]>();
byteArrayList.Add(new byte[]{1, 2, 3, 5, 9, 6, 7, 6, 45, 50, 39 });
byteArrayList.Add(new byte[]{0, 1, 0, 1, 0, 1, 0, 1, 99, 99, 99, 99, 99, 99});
byteArrayList.Add(new byte[]{2, 2, 2, 2, 3, 3, 3, 3 });
byteArrayList.Add(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 31, 21 });
byteArrayList.Add(new byte[]{1, 22, 32, 22, 3, 3, 3, 3, 12, 13, 14, 15 });
byteArrayList.Add(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 95, 85, 75});
让我们说出当前的列表索引
ListPoisition = 2;
因此列表应该从 ListPoisition == 2 到列表末尾排序。
结果列表应该是这样的:
byteArrayList = { {1, 2, 3, 5, 9, 6, 7, 6, 45, 50, 39 },
{0, 1, 0, 1, 0, 1, 0, 1, 99, 99, 99, 99, 99, 99 },
{0, 0, 0, 0, 0, 0, 0, 0, 31, 21 },
{0, 0, 0, 0, 0, 0, 0, 0, 95, 85, 75},
{1, 22, 32, 22, 3, 3, 3, 3, 12, 13, 14, 15 },
{2, 2, 2, 2, 3, 3, 3, 3 }
};
这只是一个例子,但实际列表可以包含N个byte[]。
最佳答案
可以使用下面的扩展方法
public static void PartialSort<T>(this T[] array, int startIndex, int endIndex)
{
T[] sortedList = new T[(endIndex - startIndex) + 1];
for (int i = startIndex; i <= endIndex; i++)
{
sortedList[i - startIndex] = array[i];
}
List<T> newList = new List<T>(sortedList);
newList.Sort();
sortedList = newList.ToArray();
for (int i = 0; i < sortedList.Length; i++)
array[i + startIndex] = sortedList[i];
}
如果要从位置 2 开始对列表中的每个数组进行排序,则可以执行以下操作:
var start = 2;
foreach (var entry in byteArrayList)
{
entry.PartialSort(start, entry.Length - 1);
}
这里是工作 demo
如果你想从列表中的索引 2 开始对每个数组进行排序,那么你可以执行以下操作:
var ListPosition=2;
for (var index = 0; index < byteArrayList.Count; index++)
{
if (index >= ListPosition)
byteArrayList[index].PartialSort(0, byteArrayList[index].Length - 1);
}
这里是工作 demo
已更新
根据您的评论,您只想对列表进行排序,而不是对其中的数组进行排序,因此您可以执行以下操作:
- 定义自定义比较器
- 使用List的Sort方法
比较类
public class ByteArrayComparer : IComparer<byte[]>
{
public int Compare(byte[] first, byte[] second)
{
// find the minimum length of the both arrays
var length = first.Length > second.Length ? second.Length : first.Length;
for (var index = 0; index < length; index++)
{
if (first[index] > second[index])
return 1;
if (second[index] > first[index])
return -1;
}
return 0;
}
}
你的代码应该是这样的
var ListPosition = 2;
if(ListPosition< byteArrayList.Count && ListPosition>-1)
byteArrayList.Sort(start,byteArrayList.Count - start, new ByteArrayComparer());
这里是工作 demo
关于c# - 从特定的 listindex 到 c# 中的列表末尾对 List<byte[]> 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39758166/