2011-04-04 107 views
1

我在asp.net/C#/VS2008我的Web应用程序项目和一个ArrayList中我使用.NET 3.5搜索一个ArrayList

我使用一类是添加内容到ArrayList定义如下:

ArrayList selectedRowItems = new ArrayList(); 
selectedRowItems.Add(new ShoppingCartDataStore(componentName, componentPrice, fileSize, componentDescription)); 

假设我要搜索的插件后,此ArrayList:

using System.Web; 

class ShoppingCartDataStore 
{ 
    private string componentName; 
    private string componentPrice; 
    private string componentFileSize; 
    private string componentDescription; 

    public ShoppingCartDataStore(string componentName, string componentPrice, string componentFileSize, string componentDescription){ 
     this.componentName = componentName; 
     this.componentPrice = componentPrice; 
     this.componentFileSize = componentFileSize; 
     this.componentDescription = componentDescription; 
    } 

    public string ComponentName 
    { 
     get 
     { 
      return this.componentName; 
     } 
    } 

    public string ComponentPrice 
    { 
     get 
     { 
      return this.componentPrice; 
     } 
    } 

    public string ComponentFileSize 
    { 
     get 
     { 
      return this.componentFileSize; 
     } 
    } 

    public string ComponentDescription 
    { 
     get 
     { 
      return this.componentDescription; 
     } 
    } 
} 

,我用下面的代码添加内容到ArrayList以这种方式将componentName作为键的几个值。我试着下面的代码,但我只是不能够找到一个方法来做到这一点:

ArrayList temporarySelectedItemsList = new ArrayList(); 
ArrayList presentValue = new ArrayList(); 
string key = componentName; //some specific component name 
temporarySelectedItemsList = selectedRowItems; 
for (int i = 0; i < temporarySelectedItemsList.Count; i++) 
{ 
    presentValue = (ArrayList)temporarySelectedItemsList[i]; 
} 
+1

您使用的是什么版本的.NET?如果您使用.NET 2.0或更高版本,那么您不应该使用'ArrayList'。 – 2011-04-04 23:19:00

+0

除非你的目标是.net pre v2,那么你几乎可以肯定使用通用列表 – 2011-04-04 23:20:54

+0

我使用.NET 3.5 – user691936 2011-04-04 23:22:07

回答

2
var results = selectedRowItems.OfType<ShoppingCartDataStore>().Where(x=>x.ComponentName == "foo") 

当然如果你使用一个通用的清单,而不是一个数组列表,你可以摆脱OfType的

编辑:所以,我不知道为什么你不会使用LINQ或泛型,如果你在3.5。但如果你必须:

ArrayList results = new ArrayList(); 


foreach (ShoppingCartDataStore store in selectedRowItems) 
{ 
    if(store.ComponentName == "foo"){ 
     results.Add(store); 
    } 
} 
+0

我没有在我的项目中使用linq,你能解释一下正常的C#代码吗?谢谢 – user691936 2011-04-04 23:23:24

0

我生病了,这是未经测试,但我认为它会工作。 :)

List<ShoppingCartDataStore> aList = new List<ShoppingCartDataStore>(); 
// add your data here 

string key = componentName; //some specific component name 
// Now search 
foreach (ShoppingCartDataStore i in aList) 
{ 
    if (i.ComponentName == key) 
    { 
     // Found, do something 
    } 
}