基于更改的参数列表进行搜索

时间:2015-11-03 18:52:24

标签: c# search arraylist

我有这些对象的列表:

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

一样

2 个答案:

答案 0 :(得分:1)

这是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

答案 1 :(得分:0)

## Pass a vector to sum, and it will add the elements together.
sum(1:5)

## Pass several numbers to sum, and it also adds the elements.
sum(1, 2, 3, 4, 5)

## In fact, you can pass vectors into several arguments, and everything gets added.
sum(1:2, 3:5)

## If there are missing values, the sum is unknown, i.e., also missing, ....
sum(1:5, NA)
## ... unless  we exclude missing values explicitly:
sum(1:5, NA, na.rm = TRUE)