Guid type and ( '>' greater than comparison) in LINQ to SQL

后端 未结 3 621
春和景丽
春和景丽 2021-01-18 22:24

Please, help me. I try compare two guid in .Where() query method. But I get compile error. Error 1 Operator \'>\' can not be applied to operands of type \"System.Guid\" and

相关标签:
3条回答
  • 2021-01-18 22:39

    And with :

    u.FriendID.CompareTo(startUser) > 0
    

    ?

    0 讨论(0)
  • 2021-01-18 22:42

    It doesn't make sense to apply greater than or less than to a Guid.

    0f8fad5b-d9cb-469f-a165-70867728950e and 7c9e6679-7425-40de-944b-e07fc1f90ae7

    Two Guids but which is greater? Do you drop the - and calculate the total of the HEX? or how about add the sums of the HEX between - ?

    It's just simply not done (though it could be)

    Apply logical == and != does however make sense though. The Guid struct does overload the == and != operators, so use them and you can also easily compare string values i.e.

    var isEqual = guid.ToString().Equals(otherGuid.ToString());

    0 讨论(0)
  • 2021-01-18 22:50

    I know this is an old question, but i have seen this data case before, and it might be relevant for someone in the future. This can be relevant where you for some reason have clustered your table (physically organized, default with Primary key) on a uniqueidentifier. If you need to batch read or page the table, you can end up with SQL queries that read:

    SELECT TOP (@batchsize)
        *
    FROM myTable
    WHERE UserId > @previousBatchUserId
    

    That is in general not a very optimal design, and as you have observed don't work with LINQ-to-SQL. Also, what is in a batch will change if you do the same query later after more rows are added. If you have a CreatedDate(time) column ordering by that instead would be much better. Or using the created date column as the first criteria, and then a != check on the GUID (if there can be more than one created with the same stamp). Ideally you would add a surrogate identity column (and cluster on it), and then you could filter on that ID where it is larger than of the one corresponding to your desired GUID.

    It could then look like:

    Guid startUser = //some guid
    int startUserId = Common.DataContext.Friends.Single(u => u.FriendID == startUser).Id;
    List<Friends> friends = Common.DataContext.Friends.Where(u => u.Id > startUserId);
    
    0 讨论(0)
提交回复
热议问题