c# - 我们可以用 linq 让它更简洁吗?

标签 c# linq

我很好奇是否有一种方法可以在 linq 语句本身中捕获较低的行(创建字典和循环以添加值)。现在 select new 返回一个新的匿名类型,但我想知道是否有办法让它返回一个包含所有预填充值的字典。

    XDocument reader = XDocument.Load("sl.config");
    var configValues = from s in reader.Descendants("add") select new { Key = s.Attribute("key").Value, s.Attribute("value").Value };

    Dictionary<string, string> Settings = new Dictionary<string, string>();

    foreach (var s in configValues)
    {
        Settings.Add(s.Key, s.Value);
    }

最佳答案

尝试 Enumerable.ToDictionary扩展方法。

 XDocument reader = XDocument.Load("sl.config");
 var Settings = reader.Descendants("add")
   .ToDictionary(s => s.Attribute("key").Value, s => s.Attribute("value").Value);

关于c# - 我们可以用 linq 让它更简洁吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2351920/

相关文章:

c# - 如何在 Task<int> 列表之间插入延迟?

c# - 这个冒号是什么(:) mean?

c# - LINQ 查询获取具有指定类型成员的所有实体

c# - LINQ Max 扩展方法在空集合上出错

asp.net-mvc - 如何将我的 View 模型绑定(bind)到 jqGrid?

c# - 是否可以在存储过程的输出变量中使用 MERGE 语句的 $action?

c# - WPF:如何防止 WriteableBitmap 撕裂?

C# Autoupdater.net 无法提取

c# - 为什么 ?.Any() 被归类为可为空的 bool 值?

c# - Linq to Entities 删除而不获取