1

Possible Duplicate:
Good GetHashCode() override for List of Foo objects

I have List of Objects, Object has ID, FileName, Status(Enumerator), DateStamp, UserId.
Using Linq I filter List using UserId and send it to Web App.

I need to get some kind of Unique Id for filtered result and compare it next time to detect changes for current user. If new Object added for current user or property of existing object is changed Unique Id should be different.

I have tried to use code below to get Hash Code but hash code is different for every myList object even objects and object properties are the same. Any ideas please?

myList= _queueList.GetItems(p => p.User.Id == userId)
                  .OrderByDescending(p => p.DateStamp)
                  .ToList();

myList.GetHashCode()
Community
  • 1
  • 1
Tomas
  • 17,551
  • 43
  • 152
  • 257
  • @DanielA.White that doesn't matter for this usage -- the only requirement is that if the data changes the id changes. The chance of the data changing but the hash remaining the same by accident is vanishingly small. A good hash should be acceptable for this use. – Kara Potts Aug 07 '12 at 13:50
  • @karaken12 the point is that's not what GetHashCode() is used for. I would be suprised if List provided an implementation other than the base Object.GetHashCode(), which isn't going to tell you anything about the uniqueness of the contents. – drch Aug 07 '12 at 14:01
  • @drch Isn't that exactly what [GetHashCode](http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx) is for? "A hash function must have the following properties: If two objects compare as equal, the GetHashCode method for each object must return the same value." -- If you want two lists to be equal if they contain "equal" objects, this seems entirely appropriate. See the question linked to by Hans. – Kara Potts Aug 07 '12 at 15:25
  • @karaken12 a list's hash code isn't based on its contents. If you're trying to see if a list of objects has changed, GetHashCode() won't help you. See http://pastebin.com/qzskbaFR – drch Aug 07 '12 at 15:35

2 Answers2

1
var uniqueId = string.Join(",", myList.Select(x=>x.Id.ToString()).ToArray());

If the string is very long, you could generate an md5 or sha1 and return that instead.

drch
  • 3,040
  • 1
  • 18
  • 29
1

You could leverage builtin cryptography like this:

string hash = Convert.ToBase64String(
    new SHA1CryptoServiceProvider().ComputeHash(
        Encoding.UTF8.GetBytes(
            string.Join(":", myList.Select(obj => obj.Id.ToString()).ToArray()
        )));

I put Convert.ToBase64String() to make it web-friendly (beware: the resulting string might become quite long if you have many records!)

Alex
  • 23,004
  • 4
  • 39
  • 73