Tuesday, June 17, 2008 3:01 PM hoonius

I ♥ List<>

Anyone like List<>?

Since I've been writing LINQ in my apps, i've got right into using them wherever possible.  You can fill them up with your custom objects, select, sort, the lot

 

public class TimzObject
{
     private string _Name;
     private int _Age;

     public string Name
     {
          get
          {
               return _Name;
          }
     }

     public int Age
     {
          get
          {
               return _Age;
          }
     }

     public TimzObject(string strName, int nAge)
     {
          this._Name = strName;
          this._Age = nAge;
     }

     public TimzObject()
     {


     }
}

Then make your List<>

List myList = new List<TimzObject>();
myList.Add(new TimzObject("Tim Hustler", 30));  //my real age
myList.Add(new TimzObject("Angelina Jolie", 21)); // her 'real' age (she wishes)

//sort by Age
myList.Sort(
delegate(TimzObject A, TimzObject B)
{
return A.Age.CompareTo(B.Age); 
});
I'll extend this as time allows :¬)
Filed under: , , ,

Comments

# re: I ♥ List<>

Tuesday, June 17, 2008 10:54 AM by Jon von Gillern

Couple things in the myList.Sort line

1. You don't need to use the new keyword on anonymous methods

2. Using a lambda expression will provide a condensed syntax by removing the delegate keyword and the explicit strong typing of objects A and B. The lambda looks like:

myList.Sort((a, b) => { return a.Age.CompareTo(b.Age); });

With lambdas, the parameter types are inferred based on the method signature of the delegate your method is expecting.

# re: I ♥ List<>

Tuesday, June 17, 2008 11:46 AM by hoonius

Good spot Jon.  It's amazing how relaint we've become on intellisense, well me anyway

I'm just discovering the way lambda works but i find examples out-of-context and hard to follow.  Whereas, with yours, it's a direct replacement for my own code so fits perfectly in my personal context

Thanks for posting :¬)

Leave a Comment

(required) 
(required) 
(optional)
(required)