views:

396

answers:

3

I'm trying to build a way to get the key for a given piece of text in a given resx file at runtime.

Currently, I can open and read the file (Using ResXResourceReader) but I have to use a foreach to go over the entire file.

This could be a performance issue, as some of our resx files are fairly large (in the order of 2000 strings) and we may be doing this frequently.

I'd like to use LINQ to Objects to query this, as I assume the 'where' extension is relatively optimized, however I've been unable to do so. The ResXResourceReader class has two methods 'AsQueryable()' and 'GetEnumerator()', but neither allow LINQ against their result (so 'from n in reader.AsQueryable() where' fails).

How can I LINQ against something provided by the ResXResourceReader, or is it even worth the time?

+1  A: 

Have you considered just doing some pre-processing?

You could load the Resx file, then loop over the key-value pairs, and then store them reversed in a hash table (i.e. the key in the hash table is actually the value of the resource, and the value in the hash table is the key of the resource). Then the translations of value->key would be fast. The only concern is how you handle duplicates (multiple resources with the same value).

Yuliy
+1  A: 

This isn't really worth your time. LINQ doesn't have any means of searching your .resx file any more efficiently than you could. Depending on memory usage and whether or not caching the data makes sense for you, you would probably be better off reading the entire file into a Dictionary<TKey,TValue> and doing your lookups that way.

You could, of course, create your own tuplet object to store a Key/Value pair and read in the whole file into a List of these, then allow LINQ to objects to do your querying, but this won't be as fast as a Dictionary and would require more overhead.

Adam Robinson
+1  A: 

The following code returns an IEnumerable object that allows you to use LINQ to query the contents of a resource file:

ResXResourceReader reader = new ResXResourceReader(myfile);
IEnumerable<DictionaryEntry> enumerator = reader.OfType<DictionaryEntry>();
pmarflee
I've accepted this because it works, and it does most correctly answer my immediate question. I am, however, going to take the other responses into consideration, and we may not end up actually using this.
Jeff