我们可以用linq更简洁吗?

kei*_*en7 2 c# linq

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

    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);
    }
Run Code Online (Sandbox Code Playgroud)

Den*_*s K 6

试试Enumerable.ToDictionary扩展方法.

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