How do I use LinkedList FindLast with my own type?

I am using a linked list and want to start removing items from the end of the list based on a property of the type that the list is holding.  See code snippet.

class MyType {
public long MyTypeCategoryId

LinkedList<MyType> list = new LinkedList<MyType>(...)

//Find where MyTypeCategoryId == 7
LinkedListNode<MyType> lln = list.FindLast(???);

Open in new window

Who is Participating?
käµfm³d 👽Connect With a Mentor Commented:
I don't believe you'll be able to use FindLast because it expects a reference to an existing car object--at least one that exists in the list. Is it possible to use Linq (.NET 3.5+)? If so, you could do something like:

LinkedList<Car> myList = new LinkedList<Car>();

myList.AddFirst(new Car() { Make = "Honda", Model = "Civic" });
myList.AddFirst(new Car() { Make = "Toyata", Model = "Tundra" });

Car theCar = myList.Where(c => c.Make == "Toyata").LastOrDefault();

if (theCar != null)
    // found the car!

Open in new window

käµfm³d 👽Commented:

You would need the following namespace import:

using System.Linq;

Open in new window

käµfm³d 👽Commented:
Correction to line 6 in my first post:

Car theCar = myList.LastOrDefault(c => c.Make == "Toyota");

Open in new window

Jacques Bourgeois (James Burger)Connect With a Mentor PresidentCommented:
You need to create a class that implements the IComparer interface. You can then pass that class to the Sort method of the collection:

.Sort(New DocumentationComparer())

Unfortunately, I do not have any code in C# to provide. Most of my advanced work is done in VB and the couple of such classes I have are quite involved because they can sort on many different criterias.

There is a quite simple C# example of how to implement IComparer if you lookup IComparer Interface in the documentation.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.