2015-11-03 88 views
-2

不斷變化的名單上有這些對象的列表:搜索基於關閉的參數

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

+0

代碼中的'} \t返港的這一部分首發;'爲什麼會有一個額外的''}在foreach代碼塊中還清理你的代碼在你的foreach循環格式.. – MethodMan

+0

現在ArrayList已經過時了10年。你應該使用'List'來代替。 – Servy

+1

您的搜索算法在這兩個示例之間甚至沒有一致性......目前尚不清楚您實際需要什麼。考慮一個座位,它的'Section'爲5,'Row'爲6.現在搜索一個座位,該座位的'Section'爲5,'Row'爲5.您的第一個算法不會將其添加爲搜索,但第二個會。 –

回答

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 
+0

@Servy,謝謝 - 更正。 –

+0

如果你使用'var',你也只需要調用'AsEnumerable'。如果你明確地輸入變量,這是多餘的。 – Servy

0
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()); 
+0

你不能在'ArrayList'上使用LINQ,因爲它不會強制通用'IEnumerable ' –

+0

從上面的代碼 //座位是座位類的列表 – isxaker

+0

OP意味着相當'ArrayList',因爲這是返回類型 –