简体   繁体   English

可枚举如何转换为字典?

[英]How is an Enumerable converted to a Dictionary?

I have the following code from MSDN sample : 我有来自MSDN示例的以下代码:

if (sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).Count() != 0)
{
    row = sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).First();
...

Which I refactored as follows: 我将其重构如下:

Dictionary<uint, Row> rowDic = sheetData.Elements<Row>().ToDictionary(r => r.RowIndex.Value);
if (rowDic[rowIndex].Count() != 0)
{
    row = rowDic[rowIndex];
...

Now, I sensed that if the Enumerable.ToDictionary<> method actually has to enumerate through all the data, then this would be as well redundant, but the MSDN documentation does not say anything about how this conversion takes place. 现在,我感觉到,如果Enumerable.ToDictionary <>方法实际上必须枚举所有数据,那么这也将是多余的,但是MSDN文档没有说明这种转换的方式。

The alternative I'm thinking of using is: 我正在考虑使用的替代方法是:

var foundRow = sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex);
if (foundRow.Count() != 0)
{
    row = foundRow.First();
...

However, I would like to know from possibly previous experiences which would be faster and why. 但是,我想从以前的经验中知道哪些会更快,为什么。

Thanks. 谢谢。

The cleaner alternative is: 较清洁的替代方法是:

var row = sheetData.Elements<Row>()
                   .FirstOrDefault(r => r.RowIndex == rowIndex);
if (row != null)
{
    // Use row
}

That will only iterate through the sequence once, and it will stop as soon as it finds a match. 那只会在序列中迭代一次,一旦找到匹配项,它将停止。

Both the .Count() and ToDictionary methods have to enumerate all elements to obtain the result. .Count()ToDictionary方法都必须枚举所有元素才能获得结果。

Here's the most efficient implementation: 这是最有效的实现:

var foundRow = sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex == rowIndex);
if (foundRow != null)
{
    row = foundRow;

...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM