我试图根据用户在txtDepartment.Text中输入的文本列出一些字符串。但它显示的是我拥有的所有项目,而不仅仅是BOOK类型的项目。DEPARTMENT是一个枚举,它的值类型为BOOK、NEWSPAPER和DIGITAL。有谁知道我如何在资源列表中只显示BOOK类型而不是所有项目?下面是我到目前为止的代码:
string searchdep = txtDepartment.Text;
foreach(Resource res in resourceslist)
{
if(searchdep==DEPARTMENT.BOOK)
{
lbResult.Items.Add(res);
}
}
这是我的类资源
namespace OOP_V1._3
{
public enum DEPARTMENT
{
BOOK,
NEWSPAPER,
DIGITAL
}
public enum STATUS
{
AVALIABLE,
BORROWED,
RESERVED
}
[Serializable]
public abstract class Resource : IComparable
{
public string title;
public string refno;
public DEPARTMENT department;
public STATUS status;
public string searchdep { get; set; }
public string getTitle()
{
return title;
}
public void setTitle(string iTitle)
{
this.title = iTitle;
}
public string getRefno()
{
return refno;
}
public void setRefno(string iRefno)
{
this.refno = iRefno;
}
public DEPARTMENT getDepartment()
{
return department;
}
public void setDepartment(DEPARTMENT iDepartment)
{
this.department = iDepartment;
}
public STATUS getStatus()
{
return status;
}
public void setStatus(STATUS iStatus)
{
this.status = iStatus;
}
public override string ToString() //display the books in the form of a string
{
return String.Format("Ref No: {0}, Title: {1}, Department: {2}, Status: {3}", refno, title, department, status);
}
public Resource(string refno, string title, string status)
{
this.refno = refno;
this.title = title;
if (status == "Available")
{
this.status = STATUS.AVALIABLE;
}
else if (status == "Borrowed")
{
this.status = STATUS.BORROWED;
}
else if (status == "Reserved")
{
this.status = STATUS.RESERVED;
}
}
public int CompareTo(Object obj)
{
Resource other = (Resource)obj;
int c = string.Compare(this.getTitle(), other.getTitle()); //comparing the title inputted by the user with a title from the list
return c; //returning the answer
}
}
}
首先,我建议将用户的值解析到Enum中,然后在输入无效时采取适当的操作。您可以使用Enum.TryParse
方法:
DEPARTMENT result;
if (!Enum.TryParse(searchdep, true, out result))
{
// display error message?
return;
}
然后,可以使用解析后的值进行比较:
if (result == DEPARTMENT.BOOK)
{
foreach (Resource res in resourceslist)
{
lbResult.Items.Add(res);
}
}
(我已经翻转了你的if
和foreach
块,因为没有必要在foreach
循环中反复检查searchdep
的值)
我在这里包括2个备选方案,这取决于您想要做什么。在这两种情况下,结果过滤都有效:
static void Main(string[] args)
{
List<Resource> Resources = new List<Resource> { new Resource(DEPARTMENT.DIGITAL), new Resource(DEPARTMENT.BOOK) };
List<Resource> lbResult = new List<Resource>();
string searchdep = "BOOK";
DEPARTMENT result;
//if (Enum.TryParse(searchdep, true, out result))
foreach (var res in Resources)
if (res.department == DEPARTMENT.BOOK) //or instead == result.
lbResult.Add(res);
Console.ReadLine();
}
我在代码中添加了这个小的构造函数,只是为了能够测试上面的代码。
public class Resource : IComparable
{
public Resource(DEPARTMENT dep)
{
department = dep;
}
...
}