如何实现Linq to XML Where子句的大小写不敏感匹配?
实现XML查询的大小写不敏感匹配
要实现CharacterName属性和输入的_characterName之间的大小写不敏感匹配,有两种可靠的实现方式:
方法一:统一转换为小写(或大写)后比较
将XML中的属性值和输入参数都转换为相同大小写,再做相等判断,彻底消除大小写差异的影响:
修改原代码的where条件部分:
IEnumerable<XElement> characterNames = from el in doc.Root.Elements("Setting") where ((string)el.Attribute("CharacterName")).ToLower() == _characterName.ToLower() select el;
方法二:使用String.Equals指定忽略大小写的比较规则(推荐)
这种方式更规范,还能避免因文化差异导致的异常匹配,推荐使用StringComparison.OrdinalIgnoreCase(不考虑文化的序号比较,性能更优):
IEnumerable<XElement> characterNames = from el in doc.Root.Elements("Setting") where string.Equals((string)el.Attribute("CharacterName"), _characterName, StringComparison.OrdinalIgnoreCase) select el;
额外优化建议
原代码中多次调用characterNames.FirstOrDefault()会重复遍历查询结果,建议先缓存匹配到的元素,提升效率:
var matchedCharacter = characterNames.FirstOrDefault(); if (matchedCharacter != null) { Console.WriteLine(matchedCharacter.Attribute("AccountName").Value); index[0] = matchedCharacter.Attribute("AccountName").Value; index[1] = matchedCharacter.Attribute("AccountPassword").Value; index[2] = matchedCharacter.Attribute("ServerName").Value; index[3] = matchedCharacter.Attribute("CharacterName").Value; } else { Console.WriteLine("ERROR: Could not locate login information."); }
内容的提问来源于stack exchange,提问作者bjcasey
相关产品推荐
相关产品推荐

