Link to home
Start Free TrialLog in
Avatar of Bruce
BruceFlag for United States of America

asked on

How do I get the index of an item in an IList based of that Item...?

I am trying to remove a specific Item from an IList the is found via Linq.  

How do I get the index from an item itself?

See my code below
IList<MyType> myList = new List<MyType>();
MyType myTItem = myList.OrderByDescending(x => x.YearOfService).Where(y = y.YearOfService < 2001).Last();
long indx = ??? //index of myTItem
myList.RemoveAt(indx);

Open in new window

Avatar of Carlos Villegas
Carlos Villegas
Flag of United States of America image

Try:
IList<MyType> myList = new List<MyType>();
MyType myTItem = myList.OrderByDescending(x => x.YearOfService).Where(y = y.YearOfService < 2001).Last();
long indx = myList.IndexOf(myTItem); //index of myTItem
myList.RemoveAt(indx);

Open in new window

Also:
IList<MyType> myList = new List<MyType>();
MyType myTItem = myList.OrderByDescending(x => x.YearOfService).Where(y = y.YearOfService < 2001).Last();
myList.Remove(myTItem);

Open in new window

The index must be a int (first example, line #3)
Avatar of Bruce

ASKER

"Try:"
I don't have IndexOf on my IList.

"Also:"
myList.Remove(myTItem) errors out.
Argument type 'MyType' is not assignable to parameter type 'System.Predicate<MyType>'
mmm we are missing something... I list has that method:
http://msdn.microsoft.com/en-us/library/3w0148af(v=VS.80).aspx
ASKER CERTIFIED SOLUTION
Avatar of Carlos Villegas
Carlos Villegas
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Bruce

ASKER

Sorry, I didn't represent my example well...

I was using a class and interface that were created by another developer.  The class inherited from the interface and the interface from IEnumerable.  I was under the impression that it was IList and built my example accordingly.

I've got it working now.  

I'm gladly giving the points.  Thanks for the help.