C#查找列表中的名称(用户输入)出错

时间:2019-02-06 17:11:37

标签: c#

我对C#还是很陌生,我想在列表中找到对象名称。

这是我的代码:

"class Wares
{
    string wareName;
    float warePrice, wareWeight;
    int wareStatus;

    List<Wares> warelist = new List<Wares>();



    public Wares(string WareName, float WarePrice, float WareWeight, int WareStatus)
    {

        this.wareName = WareName;
        this.warePrice = WarePrice;
        this.wareWeight = WareWeight;
        this.wareStatus = WareStatus;


        warelist = new List<Wares>();


    }

    public float Wareprice { get; set; }
    public float Wareweight { get; set; }
    public int Warestatus { get; set; }

    public string Desc()
    {

        string description = $"Denna vara heter {wareName} och kostar {warePrice}kr den väger {wareWeight}kg och det finns {wareStatus}st i lager";  

        return description;
    }

}

"public void FindInList()
    {
        Console.WriteLine("What do you want to find?");
        string userinput = Console.ReadLine();
        warelist.Contains(userinput);

    }"

Warelist是我的列表。但是我得到了错误,无法将字符串转换为Namespace.Wares

我的计划是检查列表中是否有用户输入,然后添加删除该项目的可能性。

1 个答案:

答案 0 :(得分:0)

Contains方法检查以查看提供的对象是否在List中。这意味着它期望与列表包含的对象具有相同的类型-它不会读懂您的思想,也不会搜索这些对象的每个变量。

要想做到的简洁,就需要LINQ:

warelist.Any(ware => ware.wareName == userInput);