How to compare two byte arrays with a larger or smaller operator value in C # or Linq?

I have a byte array in my first Entity Framework for SQL TimeStamps, as shown below:

 [Column(TypeName = "timestamp")]
 [MaxLength(8)]
 [Timestamp]
 public byte[] TimeStamps { get; set; }

The above property is equal to the SQL timestamp data type in C #.

In SQL Server, I can easily compare the “timestamp” as shown below ...

SELECT * FROM tableName WHERE timestampsColumnName > 0x000000000017C1A2

The same thing that I want to achieve in C # or Linq Query. Here I wrote my Linq query, which is not working correctly.

 byte[] lastTimeStamp = someByteArrayValue;
 lstCostCenter.Where(p => p.TimeStamps > lastTimeStamp);

I also tried using BitConvertercompare two-byte array which also doesn't work ...

 lstCostCenter.Where(p => BitConverter.ToInt64(p.TimeStamps, 0) > BitConverter.ToInt64(lastTimeStamp, 0));

How to compare byte arrays in C # or Linq Query.

. , , SequenceEqual , true false. , Linq , < , , SQL Server.

+4
2

- IStructuralComparable, Array :

byte[] rv1 = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x01 };
byte[] rv2 = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x05 };

var result = ((IStructuralComparable)rv1).CompareTo(rv2, Comparer<byte>.Default); // returns negative value, because rv1 < rv2

- BitConverter, , BitConverter ( - BitConverter.IsLittleEndian , true). , .

var i1 = BitConverter.ToUInt64(rv1.Reverse().ToArray(), 0);
var i2 = BitConverter.ToUInt64(rv2.Reverse().ToArray(), 0);

, Entity Framework , , Entity Framework , . IStructuralComparable ( BitConverter ), . Compare:

static class ArrayExtensions {
    public static int Compare(this byte[] b1, byte[] b2) {
        // you can as well just throw NotImplementedException here, EF will not call this method directly
        if (b1 == null && b2 == null)
            return 0;
        else if (b1 == null)
            return -1;
        else if (b2 == null)
            return 1;
        return ((IStructuralComparable) b1).CompareTo(b2, Comparer<byte>.Default);
    }
}

EF LINQ:

var result = ctx.TestTables.Where(c => c.RowVersion.Compare(rv1) > 0).ToList();

EF Compare SQL- ( * , RowVersion > @yourVersion)

+7

, , :

Func<byte[], byte[], bool> isGreater =
    (xs, ys) =>
        xs
            .Zip(ys, (x, y) => new { x, y })
            .Where(z => z.x != z.y)
            .Take(1)
            .Where(z => z.x > z.y)
            .Any();

:

byte[] rv1 = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x01 };
byte[] rv2 = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x05 };

Console.WriteLine(isGreater(rv1, rv2));
Console.WriteLine(isGreater(rv2, rv1));

... :

False
True
0

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


All Articles