Sorting a list of a list of bytes or a list of byte arrays

LINQ has excellent OrderBy functionality with ThenBy, etc., but how can I make this work on List<List<byte>>

sorting by 1st column, then 2nd, and so on.

List of byte list:

[0] = {0, 1, 2, 3, 4}
[1] = {0, 0, 2, 4, 1}
[2] = {1, 2, 2, 1, 1}
[3] = {1, 0, 2, 2, 2}

      

Actually I was doing the same thing when I was doing string [], but converting byte to string and then backwards was messy and the results were different in different ways.

I want to receive:

[0] = {0, 0, 2, 4, 1}
[1] = {0, 1, 2, 3, 4}
[2] = {1, 0, 2, 2, 2}
[3] = {1, 2, 2, 1, 1}

      

Can I use LINQ or any other library already created to do this, or maybe any guidelines for building it manually?

+3


source to share


3 answers


You can start with implementation IComparer<IList<byte>>

. For example. (omitting zero processing for brevity):

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);
    }
}

      

The above is untested (not even compiled), but should be enough to get you started.



Then you can use OrderBy

in your main list by passing an instance of that comparator:

input.OrderBy(x => x, new ByteListComparer())

      

+9


source


By the way, there is a line like this in the marked answer

for(int index = 0; index < Math.Min(x.Count, y.Count); index++)

      

therefore the function

Math.Min(x.Count, y.Count)

      



will be called as many times as iteration.

Should be

int min=Math.Min(x.Count, y.Count);
for(int index = 0; index < min; index++)

      

+1


source


This approach will work as well. But @Joe demonstrated a better performance approach.

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();
    }   
}

      

https://dotnetfiddle.net/B8kmZX

0


source







All Articles