我很好奇是否有一种方法可以在 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/