views:

35

answers:

2

I have a List of User objects from my data store.

Now once it is already in memory the only way to get a user by his ID is to use the Single extension method. This is really performance degrading.

I know I could have used a dictionary instead of a list but this would be redundant. I would have to store the Primary Key 2 times. So is there another way to do what i want?

BTW I am making a custom class that can do something like this, but i was hoping for something out of the box.

A: 

You could save your in-memory users in a KeyedCollection.

Mark Seemann
+1  A: 

Assuming the primary key is a reference type, you'd only be storing a reference to the primary key twice.

Have you tried using Dictionary<,> and found it doesn't work well enough? It's certainly the most natural solution. KeyedCollection<,> (suggested by Mark) would certainly work too, but requires you to derive from the class - and I wouldn't like to guarantee it'll actually save any memory. (You'd need to know the implementation details - it could easily just use a Dictionary internally, for example.)

Jon Skeet
I think i'll try the KeyedCollection, it seems much cleaner.
diamandiev
@diamendev: If you say so. I'd personally say a single call of `list.ToDictionary(x => x.Id)` is pretty simple, but there we go... Admittedly `KeyedCollection` helps if you want to add things to it afterwards.
Jon Skeet