LINQ 到 resx 文件?
我正在尝试构建一种方法来在运行时获取给定 .resx
文件中给定文本片段的密钥。
目前,我可以打开并读取该文件(使用 ResXResourceReader
),但我必须使用 foreach
来遍历整个文件。
这可能是一个性能问题,因为我们的一些 .resx
文件相当大(大约 2000 个字符串),而且我们可能经常这样做。
我想使用 LINQ to Objects 来查询它,因为我假设 where
方法相对优化,但我一直无法这样做。 ResXResourceReader
类有两个方法 AsQueryable()
和 GetEnumerator()
,但都不允许 LINQ 针对其结果(因此 from n in reader.AsQueryable() 其中
失败)。
我如何针对 ResXResourceReader
提供的内容进行 LINQ,或者是否值得花时间?
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
method 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下代码返回一个 IEnumerable 对象,该对象允许您使用 LINQ 查询资源文件的内容:
The following code returns an IEnumerable object that allows you to use LINQ to query the contents of a resource file:
您是否考虑过只进行一些预处理?
您可以加载 Resx 文件,然后循环键值对,然后将它们反转存储在哈希表中(即哈希表中的键实际上是资源的值,而哈希表中的值是资源的键)。 那么 value->key 的翻译就会很快。 唯一关心的是如何处理重复项(具有相同值的多个资源)。
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).
这真的不值得你花时间。 LINQ 没有任何方法可以比您更有效地搜索 .resx 文件。 根据内存使用情况以及缓存数据是否对您有意义,您可能最好将整个文件读入
Dictionary
并以这种方式进行查找。当然,您可以创建自己的 tuplet 对象来存储键/值对并将整个文件读入这些文件的列表中,然后允许 LINQ to 对象执行查询,但这不会像
字典
并且需要更多的开销。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.