tags:

views:

93

answers:

2

Say I have a class that looks something like this:

class SomeClass {
    int m_member;

    public int Member {
        get { return m_member; }
        set { m_member = value; }
    }
}

And somewhere else, I have a list of type List<SomeClass> list.

If I want to search the list for a particular instance of the class, I can just do

int index = list.IndexOf(someInstance);

But if I want to search the list by Member, I have to do this:

int index = -1;
for (int i = 0; i < list.Count; i++) {
    if (list[i].Member == someMember) {
        index = i;
        break;
    }
}

Is there a better way to do this?

+6  A: 
int index = list.FindIndex(m => m.Member == someMember);
itowlson
If you need the item *instead* of the index, you can use `Find()` instead of `FindIndex()` (Not what the OP asked for, just an FYI).
280Z28
Thanks 280Z28, that comes in useful elsewhere.
Matthew
+2  A: 

If you can use Linq

SomeClass aClasss = list.FirstOrDefault(item => item.Member == someMember);
Pierre-Alain Vigeant
If you're using `List<T>`, this isn't what you want, but it does work for finding an item in an enumeration - note that it doesn't find the index of the item though.
280Z28