question

MarkusFreitag-0088 avatar image
0 Votes"
MarkusFreitag-0088 asked TimonYang-MSFT edited

Tuple<int, int> Compare operator

Hello,

if I compare two tuples always is null, why?

 //What am I doing wrong?
 //I have two tuples and want to compare for equality.
 //Is always zero, only when I go through the list, it matches.
    
    
 public Tuple<int, int> Id { get; set; }
    
    
 protected readonly Tuple<int, int> m_id;
 public Tuple<int, int> Id { get { return m_id; } }  
    
    
    
 var ret = ListID.FirstOrDefault(x => x.Id == conv.Id);
 ret = ListID.Where(x => x.Id == conv.Id).FirstOrDefault();
    
 foreach (var item in ListID)
 {
     if (item.Id.Item1 == conv.Id.Item1 && item.Id.Item2 == conv.Id.Item2)
     {
         ret = item;
         break;
     }
 }
    
 if (ret != null)


Thanks for tips in advance.

dotnet-csharp
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Do not use "==" to compare two instances of reference types, the result must be false, unless this type overloads it, but in Tuple, no operator is overloaded.
If the equals method is not overridden, the equals comparison will get the same result. But in this class, the equals method is overridden, so Viorel-1's solution can work.
Source code

1 Vote 1 ·

Hello,
Yes, works with equal. Thanks.

0 Votes 0 ·

1 Answer

Viorel-1 avatar image
1 Vote"
Viorel-1 answered MarkusFreitag-0088 commented

Try this:

 var ret = ListID.FirstOrDefault(x => x.Id.Equals(conv.Id));


· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hello,
Yes, works with equal. Thanks.

0 Votes 0 ·