Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 对照用户输入检查列表?_C#_List_Input - Fatal编程技术网

C# 对照用户输入检查列表?

C# 对照用户输入检查列表?,c#,list,input,C#,List,Input,我试图检查列表是否包含用户输入的值。用户输入位于名为txtId的文本框中,它是一个int。如果用户ID已经存在于列表中它必须从我的类中抛出一个异常 这样做时,我会收到一个错误,指出Contains()有一些无效参数: private void btnAddClass_Click(object sender, EventArgs e) { Classes newClass; // Open new form to input data

我试图检查
列表
是否包含用户输入的值。用户输入位于名为
txtId
文本框中,它是一个
int
。如果
用户ID
已经存在于
列表中
它必须从我的类
中抛出一个异常

这样做时,我会收到一个错误,指出
Contains()
有一些无效参数:

 private void btnAddClass_Click(object sender, EventArgs e)
 {
        Classes newClass;
         // Open new form to input  data
            AddNewClass add_form = new AddNewClass();
            if (add_form.ShowDialog() == DialogResult.OK)
            {
                newClass = new Classes();
                // Get new  data from second form
                newClass = add_form.ExtractData();
               //check if id already exists in the list
                **if (l.fitnessClasses.Contains(newClass.Id))
                {
                    //throw an exception
                }
                else
                {**
                    // Add the new class to  file
                    l.AddClass(newClass);
                    lstClasses.Items.Clear();
                    //sort the list by ID
                    l.fitnessClasses.Sort((a, b) => a.Id.CompareTo(b.Id));

                    foreach (Classes cl in l.fitnessClasses)
                    {
                        lstClasses.Items.Add(cl);  //add  to list box
                    }


                    // Display new  
                    MessageBox.Show(newClass.Display());
                }
            }     
    }

重写
中的
Equals
GetHashCode
方法(因为您的类需要知道如何比较实例,请参阅了解如何比较),然后您可以调用:

l.fitnessClasses.Contains(newClass); 
或者使用

l.fitnessClasses.Contains(p=> p.Id == newClass.Id)

如果你熟悉linq,你可以做如下事情

if ( l.fitnessClasses.Any(x=> x.Id == newClass.ID)) {...}

添加类等的定义。您正在使用变量l。这是什么定义?