字节列表或字节数组列表的排序列表
Sorting list of list of bytes or list of byte arrays
LINQ 具有强大的 OrderBy 功能以及 ThenBy 等,但我如何才能在 List<List<byte>>
上进行这项工作以按第一列排序,然后按第二列排序,依此类推。
字节列表列表:
[0] = {0, 1, 2, 3, 4}
[1] = {0, 0, 2, 4, 1}
[2] = {1, 2, 2, 1, 1}
[3] = {1, 0, 2, 2, 2}
实际上,我在制作 string[] 时只是做了同样的事情,但是将字节转换为字符串然后再转换回来很混乱,并且由于某种原因结果有所不同。
我想得到:
[0] = {0, 0, 2, 4, 1}
[1] = {0, 1, 2, 3, 4}
[2] = {1, 0, 2, 2, 2}
[3] = {1, 2, 2, 1, 1}
是否可以使用某些 LINQ 或任何其他已经创建的库来执行此操作,或者是否有任何关于如何手动创建它的建议?
您可以从实施 IComparer<IList<byte>>
开始。例如。 (为简洁起见省略空值处理):
public class ByteListComparer : IComparer<IList<byte>>
{
public int Compare(IList<byte> x, IList<byte> y)
{
int result;
for(int index = 0; index<Min(x.Count, y.Count); index++)
{
result = x[index].CompareTo(y[index]);
if (result != 0) return result;
}
return x.Count.CompareTo(y.Count);
}
}
以上内容未经测试(甚至未编译),但应该足以让您入门。
然后您可以在主列表中使用 OrderBy
,传入此比较器的一个实例:
input.OrderBy(x => x, new ByteListComparer())
这种方法同样有效。但是@Joe 展示了性能更好的方法。
public static void Main()
{
List<List<Byte>> bytes = new List<List<Byte>>(){
new List<Byte> {0, 1, 2, 3, 4},
new List<Byte> {0, 0, 2, 4, 1},
new List<Byte> {1, 2, 2, 1, 1},
new List<Byte> {1, 0, 2, 2, 2}
};
var result = bytes.OrderBy(x => String.Join(String.Empty, x));
foreach (var list in result)
{
foreach (var bit in list)
Console.Write(bit);
Console.WriteLine();
}
}
顺便说一句,在标记的答案中有这样一行
for(int index = 0; index < Math.Min(x.Count, y.Count); index++)
所以,函数
Math.Min(x.Count, y.Count)
将在迭代持续时调用多次。
必须
int min=Math.Min(x.Count, y.Count);
for(int index = 0; index < min; index++)
LINQ 具有强大的 OrderBy 功能以及 ThenBy 等,但我如何才能在 List<List<byte>>
上进行这项工作以按第一列排序,然后按第二列排序,依此类推。
字节列表列表:
[0] = {0, 1, 2, 3, 4}
[1] = {0, 0, 2, 4, 1}
[2] = {1, 2, 2, 1, 1}
[3] = {1, 0, 2, 2, 2}
实际上,我在制作 string[] 时只是做了同样的事情,但是将字节转换为字符串然后再转换回来很混乱,并且由于某种原因结果有所不同。
我想得到:
[0] = {0, 0, 2, 4, 1}
[1] = {0, 1, 2, 3, 4}
[2] = {1, 0, 2, 2, 2}
[3] = {1, 2, 2, 1, 1}
是否可以使用某些 LINQ 或任何其他已经创建的库来执行此操作,或者是否有任何关于如何手动创建它的建议?
您可以从实施 IComparer<IList<byte>>
开始。例如。 (为简洁起见省略空值处理):
public class ByteListComparer : IComparer<IList<byte>>
{
public int Compare(IList<byte> x, IList<byte> y)
{
int result;
for(int index = 0; index<Min(x.Count, y.Count); index++)
{
result = x[index].CompareTo(y[index]);
if (result != 0) return result;
}
return x.Count.CompareTo(y.Count);
}
}
以上内容未经测试(甚至未编译),但应该足以让您入门。
然后您可以在主列表中使用 OrderBy
,传入此比较器的一个实例:
input.OrderBy(x => x, new ByteListComparer())
这种方法同样有效。但是@Joe 展示了性能更好的方法。
public static void Main()
{
List<List<Byte>> bytes = new List<List<Byte>>(){
new List<Byte> {0, 1, 2, 3, 4},
new List<Byte> {0, 0, 2, 4, 1},
new List<Byte> {1, 2, 2, 1, 1},
new List<Byte> {1, 0, 2, 2, 2}
};
var result = bytes.OrderBy(x => String.Join(String.Empty, x));
foreach (var list in result)
{
foreach (var bit in list)
Console.Write(bit);
Console.WriteLine();
}
}
顺便说一句,在标记的答案中有这样一行
for(int index = 0; index < Math.Min(x.Count, y.Count); index++)
所以,函数
Math.Min(x.Count, y.Count)
将在迭代持续时调用多次。
必须
int min=Math.Min(x.Count, y.Count);
for(int index = 0; index < min; index++)