Monday, February 11, 2013

Sorting ArrayList with Linq

This was my first forray into Linq, so I thought I'd post it in case I need it again in the near future.

I needed a list of user to populate a DropDownList.  In DotNetNuke, you can get an ArrayList of all users on the system with a call to: UserController.GetUsers(int PortalID).

The problem is the list is sorted by UserID, so when you open the DDL, you'll see all the users in what seems to be random order.  I wanted the list to be sorted by LastName, FirstName without having to write some sort of IComparer.

This is a great use case for Linq ( I've heard a lot about it, but never used it).

ArrayList a = UserController.GetUsers(0);
var so = from UserInfo s in a orderby s.LastName,s.FirstName select s;
ddlUser.DataSource = so;
ddlUser.DataValueField = "UserID"; // Alias Name from Sproc
ddlUser.DataTextField = "DisplayName";   // Alias name from sproc
ddlUser.Items.Insert(0, new ListItem("Select One", "0")); // Adds items to DDL

If you are using a custom object (ie UserInfo), then you must explicitly declare the type.
When using LINQ to query non-generic IEnumerable collections such as ArrayList, you must explicitly declare the type of the range variable to reflect the specific type of the objects in the collection.