Moshe Levi
Moshe Levi

Reputation: 3493

NHibernate - Getting the results as an IDictionary instead of IList

I'm using NHibernate as a persistency layer and I have many places in my code where I need to retrieve all the columns of a specific table (to show in a grid for example) but i also need a fast way to get specific item from this collection.

The ICriteria API let me get the query result either as a unique value of T or a IList of T. I wonder if there is a way to make NHibernate give me those objects as an IDictionary where the key in the object's Id and the value is the object itself. doing it myself will make me iterate all over the original list which is not very scalable.

Thank you.

Upvotes: 1

Views: 469

Answers (1)

Jérôme Laban
Jérôme Laban

Reputation: 5282

If you are working with .NET 3.5, You could use the Enumerable() method from IQuery, then use the IEnumerable<T>.ToDictionary() extension method :

    var dictionary = query.Enumerable().ToDictionary(r => r.Id);

This way, the list would not be iterated twice over.

You mention using ICriteria, but it does not provide a way to lazily enumerate over items, whereas IQuery does.

However, if the number of items return by your query is too big, you might want to consider querying the database with the key you'd have used against the IDictionary instance.

Upvotes: 1

Related Questions