Linq to XMLWhere 子句不区分大小写

问题描述 投票:0回答:1

我使用此代码来检索存储在 XML 文件中的登录信息。我遇到的问题是我想让“where”条件不区分大小写,以便它可以更轻松地匹配用户可能输入的_characterName。如何使整个事情不区分大小写?

public static string[] GetInformationXML(string _characterName)
    {
        string[] index = new string[4];

        try
        {
            string dbFilePath = String.Format("{0}/.NET Programs/Saved Data/Data.xml", HomeDirectory);

            if (!File.Exists(dbFilePath))
            {
                Console.WriteLine("ERROR! Unable to find database file.");
                return index;
            }

            var doc = XDocument.Load(dbFilePath);
            
            IEnumerable<XElement> characterNames =
                from el in doc.Root.Elements("Setting")
                where (string)el.Attribute("CharacterName") == _characterName.ToLower()                    
                select el;
            
            Console.WriteLine($"Found {characterNames.Count()} entries matching [{_characterName}]");
                                         

            if (characterNames.Count() > 0)
            {
                Console.WriteLine(characterNames.FirstOrDefault().Attribute("AccountName").Value);
                
                index[0] = characterNames.FirstOrDefault().Attribute("AccountName").Value;
                index[1] = characterNames.FirstOrDefault().Attribute("AccountPassword").Value;
                index[2] = characterNames.FirstOrDefault().Attribute("ServerName").Value;
                index[3] = characterNames.FirstOrDefault().Attribute("CharacterName").Value;
            }
            else
            {
                Console.WriteLine("ERROR: Could not locate login information.");
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }

        return index;
    }
c# xml linq-to-xml
1个回答
0
投票

您可以使用 string.Compare(string, string, bool):

where string.Compare((string)el.Attribute("CharacterName"), _characterName, true) == 0 

https://learn.microsoft.com/en-us/dotnet/api/system.string.compare?view=net-8.0#system-string-compare(system-string-system-string-system-boolean)

© www.soinside.com 2019 - 2024. All rights reserved.