ArrayList.IndexOf( wild card? )
I'm trying to find the index of the first element of an ArrayList whose 'tag' property does not 开发者_JAVA技巧equal null.
I thought I could do something to the effect of
ArrayList.IndexOf(p => p.tag != null);
or
ArrayList.IndexOf(*.tag != null);
but neither of these work. Is there a way to use IndexOf with just a property of an object?
Try Array.FindIndex
:
Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the entire Array.
If you switch to using a generic List instead of ArrayList, you can do this:
int index = list.FindIndex(p => p.tag != null);
Otherwise, you're stuck having to manually (gasp) loop through the array list.
The problem with IndexOf is that you have to use as a parameter an Object in the collection. It is not a LINQ extension. That is why it fails because your lambda is not in the collection.
You could also use the following LINQ query
ArrayList.IndexOf(ArrayList.First( x => p.tag != null ))
But regarding the performance it'll be a bit poor (looking through the collection twice)
You should rather refactor your code as suggested by the smart answers around mine.
If you are wanting to do this while still using the ArrayList you can simply call ToArray() then do your FindIndex
if you know the type of the objects you could do something like this
ArrayList list = ...;
var elem = list.Cast<T>().Select((item,i) => new {item,Index = i}).FirstOrDefault(p => p.item.tag == null);
var index = elem != null ? elem.Index : -1;
will work if you know there's at least one (not that effecient mind you
Cast turns an IEnumerable
into a IEnumerable<T>
opening up the door to the rest of LINQ
int index = a.Cast<T>()
.Select((p, q) => p != null && p.tag != null ? q + 1 : 0)
.FirstOrDefault(p => p > 0) - 1;
Returns -1
if no element found.
精彩评论