搜索一个arraylist

时间:2011-04-04 23:07:52

标签: c# .net-3.5 arraylist

我在asp.net/C#/VS2008的web应用程序项目中有一个arraylist,我正在使用.net 3.5

我正在使用一个定义如下的类向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添加内容:

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

假设我想以这种方式添加几个值并以componentName作为键来搜索这个arraylist。我尝试了以下代码,但我无法找到一种方法:

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];
}

2 个答案:

答案 0 :(得分:2)

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

当然,如果你使用的是通用列表而不是arraylist,你可以摆脱OfType

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

ArrayList results = new ArrayList();


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

答案 1 :(得分: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
    }
}