根据不断变化的参数列表进行搜索
本文关键字:列表 搜索 参数 变化 | 更新日期: 2023-09-27 18:20:28
我有这些对象的列表:
public class seat
{
public String id, tooltip;
public String Section, Row, Number;
public Boolean Taken;
}
我想建立一个函数来搜索类的元素。然而,我不会总是搜索所有的元素。
我知道我可以用一个循环和一些if语句来实现这一点。按照的思路说话
public ArrayList searchArray(String section, String row, String number)
{
ArrayList searched = new ArrayList();
foreach(seat item in seats)//seats is a list of the seat class
{
if(section!="" && row!=""&& id!="")
{
if(item.Section==section && item.Row==row &&item.id==id)
searched.Add(item);
}
else if(section!="" && row!="")
{
if(item.Section==section && item.Row==row)
searched.Add(item);
}
else if(row!="")
{
if(item.Row==row)
searched.Add(item);
}
/////Continue this for all the other combinations of searching
}
return searched;
}
我也可以对它进行几个循环,比如
if(Section!="")
foreach(seat item in seats)
if(item.Section==section)
searched.Add(item);
seats = searched;
search.Clear();
if(id!="")
foreach(seat item in seats)
if(item.id==id)
searched.Add(item);
seats = searched;
search.Clear();
if(row!="")
foreach(seat item in seats)
if(item.Row==row)
searched.Add(item);
所以第一个是乏味的,需要大量难看的代码。
第二个稍微好一点,但需要我多次浏览列表。更具体地说,它要求我浏览我正在查找的每个参数的列表。
有没有一种方法可以做到这一点,你只需添加你想查找的参数,然后进行搜索。有点像生成一个要搜索的sql查询。
不那么重要,但如果它能起作用,那将是令人惊讶的,那就是甚至允许搜索范围。类似id>2 && id<12
IEnumerable<>
就是你的朋友!
IEnumerable<seat> query = seats.AsEnumerable();
if(!string.IsNullOrEmpty(section))
query = query.Where(s => s.Section == section);
if(!string.IsNullOrEmpty(row))
query = query.Where(s => s.Row == row);
if(!string.IsNullOrEmpty(id))
query = query.Where(s => s.Id == id);
List<seat> results = query.ToList(); // deferred execution
ArrayList searched = new ArrayList(
seats.Where(c => c.Section == section && !string.IsNullOrEmpty(section))
.Where(c => c.Row == row && !string.IsNullOrEmpty(row))
.Where(c => c.id == id && !string.IsNullOrEmpty(id)).ToList());