无法从“字符串”转换为“对象”

时间:2019-05-21 22:58:27

标签: c# queue contains

我正在做作业,我无法在需要查看队列中是否包含名称的地方做这部分:

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!");
        }
    }
}

我希望它可以向我显示完整的队列(姓名,生日,年龄)

1 个答案:

答案 0 :(得分:0)

要按名称查找匹配的人,请按名称过滤队列,然后查找任何剩余的匹配项。假设队列中只有一个匹配项,则将第一个匹配项打印给用户。如果person是类而不是struct,则也可以只使用FirstOrDefault并检查是否为null,但使用struct可能是最简单的方法。

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!");
}

关于您的评论,您的老师尚未覆盖LINQ,这是另一个版本。至此,我基本上正在为您做功课,但是在尝试代码时,请尽最大努力真正了解正在发生的事情。

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!");
    }
}
相关问题