开发者

searching an arraylist

I have a arraylist in my web application project in asp.net/C#/VS2008 and I'm using .net 3.5

I'm adding contents to the arraylist using a class which is defined as follows:

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

and I'm adding contents to the arraylist by following code:

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

Suppose I want to search this arraylist after adding few values in this manner with componentName as the key. I tried the following code but I'm just not able to find a way to do this:

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


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

of course you could get rid of the OfType if you were using a generic list rather than a arraylist

EDIT: So, I have no idea why you would NOT use LINQ or generics if you are in 3.5. But if you must:

ArrayList results = new ArrayList();


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


I'm sick and this is untested, but I think it'll work. :)

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜