Ok so for the last few things I've been showing a more dynamic approach to linq queries , mostly dealing with collections rather than say linq to sql. Now take the new method:
public List<K> SelectFromUserList<K, L>(Func<User, K> selectMethod, Func<User, L> orderBy, List<User> userList)
{
List<K> userList = new List<K>();
userList = userList.OrderBy(orderBy).Select(selectMethod).ToList();
return userList;
}
and the call was this:
List<String> newList = userList.Select(selectUser => selectUser.Name, orderUser => orderUser.ID, userList);
Let's say you have two needs, selecting all the userNames and all the IDs. You could go ahead and call that method twice and inserting the lambda expressions. But let's say you want to be able to mix and match things. Say select user names and order by user id or maybe select user names and order by use names. Well there's a solution to avoid rewriting the lambda expressions:
Func<User, Int32> selectUserID = currentUser => currentUser.UserID;
Func<User, String>selectUserName = currentUser => currentUser.UserName;
Func<User, Int32> orderByUserID = currentUser => currentUser.UserID;
Func<User, String> orderByUserName = currentUser => currentUser.UserName;
What the? See a while ago I had a method to pass back the expression, but in this case there's nothing to create the expression from (a passed in parameter) since they are really simple expressions. How would I use them?
List<Int32> userIDs;
List<User> userList;
List<String> userNames;
userIDs = SelectFromUserList(selectUserID, orderByUserID, userList);
userNames = SelectFromUserList(selectUserName, orderByUserID, userList);
Pretty nice huh?
No comments:
Post a Comment