使用 Linq to XML 仅选择元素的前 'n' 个字符

Selecting only first 'n' characters of an Element with Linq to XML

下面的代码行为我提供了一个包含所有时区的列表。

List<string> _timeZones = xdoc.Descendants("TimeZone").Select(x => x.Value).ToList();

但是,在这个特定列表中,我宁愿只包含前 11 个字符。

有人知道如何在上面的 Linq 语句中包含这个吗?

非常感谢您的帮助,

乔伊

您可以添加 Substring 但限制为长度:

List<string> _timeZones = xdoc.Descendants("TimeZone").Select(x => x.Value.Substring(0, Math.Min(11, x.Value.Length))).ToList();