Manipulating Generic List<T>

You can find a lot of articles on the internet that explain .Sort() and .Find() methods, but I'll explain the shortest way to do so.

Sorting

Suppose you have the User object that has Name, Age, Address and Phone properties and that you want to sort the list of Users by Name. The code will look like this:

Users.Sort(delegate(User a, User b) { return String.Compare(a.Name, b.Name); });

Finding objects

You can search for an object inside a list by any condition you wish. For example, if you want to find a user that have name "John", you'll do the next:

Users.Find(delegate(User u) { return u.Name == "John"; });

This will return the first object in the list that matches this condition.

But what if you want to find all users that are older than 20? You'll do something like this:

Users.FindAll(delegate(User u) { return u.Age >= 21; });

This will return a new list of User objects that match this condition.

Removing objects

It is easy to remove a single object from the list. Just call .Remove() method and pass the object you wan to remove as an argument.

Users.Remove(SomeUser);

Note that all properties of SomeUser object must match the item in the list you wish to delete

But if you want to make a condition for deleting items, you will use .RemoveAll() methods. It's usage is similar to Find and FindAll methods. In the example below, we'll remove all Users that are younger than 21.

Users.RemoveAll(delegate(User u) { return u.Age < 21; });

Published Wednesday, November 14, 2007 11:14 AM by janko
Filed under:
Powered by Community Server (Commercial Edition), by Telligent Systems