如何将Enumerable转换为Dictionary
本文关键字:Dictionary 转换 Enumerable | 更新日期: 2023-09-27 18:12:44
我有以下MSDN示例代码:
if (sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).Count() != 0)
{
row = sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).First();
...
我将其重构如下:
Dictionary<uint, Row> rowDic = sheetData.Elements<Row>().ToDictionary(r => r.RowIndex.Value);
if (rowDic[rowIndex].Count() != 0)
{
row = rowDic[rowIndex];
...
现在,我感觉到如果Enumerable.ToDictionary<>方法实际上必须枚举所有数据,那么这将是多余的,但是MSDN文档没有说明这种转换是如何发生的。
我正在考虑使用的替代方案是:
var foundRow = sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex);
if (foundRow.Count() != 0)
{
row = foundRow.First();
...
但是,我想从以前的经验中知道哪一种更快,为什么。
谢谢。
更简洁的方法是:
var row = sheetData.Elements<Row>()
.FirstOrDefault(r => r.RowIndex == rowIndex);
if (row != null)
{
// Use row
}
只遍历序列一次,一旦找到匹配项就会停止。
.Count()
和ToDictionary
方法都必须枚举所有元素才能获得结果。
var foundRow = sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex == rowIndex);
if (foundRow != null)
{
row = foundRow;
...