Search code examples
c#queuecontains

cannot convert from 'string' to 'object'


I'm doing homework and I can't do this part where I need to see if a name is contained in the queue:

public struct person
{
    public string name;
    public string bday;
    public int age;
}

class Program
{
    static void Main(string[] args)
    {
        person personaStruct = new person();
        Queue<person> personQueue = new Queue<person>();

        Console.WriteLine("Type a name");
        personStruct.name = Console.ReadLine();

        if (personQueue.Contains(personStruct.name))
        {
            Console.WriteLine(personStruct.name);
            Console.WriteLine(personStruct.bday);
            Console.WriteLine(personStruct.age);
        }
        else
        {
            Console.WriteLine("Doesn't exist!");
        }
    }
}

I expect it to show me the complete queue(name, bday, age)


Solution

  • To find a matching person by name filter your queue by name, then look for any remaining matches. Take the first match and print that to the user assuming there can only be one match in your queue. If person was a class instead of struct you could also just use FirstOrDefault and check for null but with a struct this might be the simplest way.

    var matchingPeopele = personQueue.Where(p => p.name == personStruct.name);
    if (matchingPeopele.Any())
    {
        var match = matchingPeopele.First();
        Console.WriteLine(match.name);
        Console.WriteLine(match.bday);
        Console.WriteLine(match.age);
    }
    else
    {
        Console.WriteLine("Doesn't exist!");
    }
    

    With respect to your comment, that your teacher hasn't covered LINQ yet, here's another version. At this point I'm basically doing your homework for you but please try your best to really understand what's going on as you try out the code.

    static void Main(string[] args)
    {
        person personStruct = new person();
        Queue<person> personQueue = new Queue<person>();
    
        Console.WriteLine("Type a name");
        personStruct.name = Console.ReadLine();
    
        var personFound = false;
        foreach(var p in personQueue)
        {
            if (p.name == personStruct.name)
            {
                personFound = true;
                Console.WriteLine(p.name);
                Console.WriteLine(p.bday);
                Console.WriteLine(p.age);
                break;
            }
        }
        if (!personFound)
        {
            Console.WriteLine("Doesn't exist!");
        }
    }