2011-06-20 71 views
1

我正在处理一些遗留代码,所以在这里不能使用通用列表。我有一个ArrayList从数据层方法返回。最后每个项目由一个ID和一个说明字段组成。我想循环访问ArrayList并在Description字符串上搜索匹配项 - 任何想法?正在搜索一个ArrayList

格式

ID DESCRIPTION 
1  SomeValue 

我知道我能做到这一点:

bool found = false; 
if (arr.IndexOf("SomeValue") >= 0) 
{ 
    found = true;  
} 

但是,有没有办法做一个字符串比较特定说明价值?

UPDATE

修订西雅图獾的回答版本:

for (int i = 0; i < arr.Count; i++) 
{ 
    if (arr[i].ToString() == "SomeValue") 
    { 
     // Do something 
     break; 
    } 
} 
+0

因此,这段代码不能使用Linq的对象? –

+0

这是正确的... – IrishChieftain

+0

可能重复的[ArrayList Search .net](http://stackoverflow.com/questions/2098019/arraylist-search-net) –

回答

1

我可能在你的问题中遗漏了一些东西,因为这看起来很直截了当。但后来我很老派......

这是否对您有帮助?

protected void Page_Load(object sender, EventArgs e) 
{ 
    ArrayList arrSample = new ArrayList(); 

    // populate ArrayList 
    arrSample.Items.Add(0, "a"); 
    arrSample.Items.Add(1, "b"); 
    arrSample.Items.Add(2, "c"); 

    // walk through the length of the ArrayList 
    for (int i = 0; i < arrSample.Items.Count; i++) 
    { 
     // you could, of course, use any string variable to search for. 
     if (arrSample.Items[i] == "a") 
      lbl.Text = arrSample.Items[i].ToString(); 
    } 
} 

正如我所说,不知道我是否在你的问题中遗漏了某些东西。 獾

+0

标记为答案..我稍微调整了代码,因为ArrayList没有Items属性...请参阅原始帖子中的更新。谢谢! :-) – IrishChieftain

2
bool found = false; 
foreach (Item item in arr) 
{ 
    if ("Some Description".Equals (item.Description, StringComparison.OrdinalIgnoreCase)) 
    { 
     found = true; 
     break; 
    } 
} 
+0

出于某种原因,没有为ArrayList的Item属性获取intellisense。我正在使用System.Collections指令 - 这是一个库类... – IrishChieftain

+0

你的数组中有什么样的对象?我上面的代码假定类型是'Item',但是你可以用类名替换Item。 –

+0

它是从SPROC返回的ArrayList。每个对象由一个ID和Description域组成。也许作者应该使用一个DataSet?无论哪种方式,我坚持与ArrayList。尝试替代对象,但得到“对象不包含描述的定义”错误消息... – IrishChieftain

0
foreach(object o in arrayList) 
{ 
    var description = o.GetType().GetProperty("Description").GetValue(o, null); 
    if("some description".Equals(description)) 
    { 
     //do something 
    } 

} 
0

你肯定你不能使用LINQ?你运行的是什么版本的框架?

仅仅因为这不是一个泛型类型并不意味着你不能这样做。考虑arr.Cast(YourType).Where(...)。

+1

它被标记为'.net-1.1',LINQ不存在它。泛型也不是扩展方法。 – vcsjones

+0

ooohhh,1.1。很抱歉听到!:)检查agent-j的答案,应该这样做。 – mtazva

0

如果您有一个ArrayList,请尝试ArrayList的“Contains”或“BinarySearch”内置函数。

protected void Page_Load(object sender, System.EventArgs e) 
    { 
    ArrayList alArrayList = new ArrayList(); 
    alArrayList.Insert(0, "a"); 
    alArrayList.Insert(1, "b"); 
    alArrayList.Insert(2, "c"); 
    alArrayList.Insert(3, "d"); 
    alArrayList.Insert(4, "e"); 

    //Use Binary Search to find the index within the array 
    if (alArrayList.BinarySearch("b") > -1) { 
      txtTemp.Text += "Binary Search Array Index: " + alArrayList.BinarySearch("b").ToString; 
    } 

    //Alternatively if index not needed use Contains function 
    if (alArrayList.Contains("b")) { 
      txtTemp.Text += "Contains Output: " + alArrayList.Contains("b").ToString; 
    } 
}