Search code examples
c#xmllinq-to-xml

Linq to XML Where Clause Case Insensitive


I'm using this code to retrieve login information that is stored in a XML file. The problem I am running into is I want to make the 'where' condition case insensitive so that it can more easily match _characterName that a user might type in.

How do I make the whole thing case-insensitive?

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;
}

Solution

  • You can use 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)