Showing posts with label Anonymous Types. Show all posts
Showing posts with label Anonymous Types. Show all posts

Tuesday, August 26, 2008

And then you hit the wall.

So as this dynamic nonsense continues, there is a sticking point to how much fun I can have. The wall? Anonymous types and generic declarations.

Here's the old:
  Func<User, Int32> selectUserID = currentUser => currentUser.UserID;
Great if I want to select userIDs, but what if I want UserIDs AND UserNames... Easy right?
 userList.Select(currentUser => new { currentUser.ID, currentUser.UserName });
Now this is the old way, but I want the new way... IE the Func way. Problem is here
  Func<User, EHH??> selectUserID = currentUser =>  new { currentUser.ID, currentUser.UserName };
You see, there's a problem. What the hell do I put at the return type? Fact is, without creating a method that passes back a Func or a class that has UserName and UserID properties, I'm screwed. Now from what I read here I think I get it. First take the func:
  Func<K, T>
I have K and T that the compiler has to figure out what they are. Well it's safe to say in the example User is K, but what is T? Well it has to figure that out from the Lamdba expression. The lambda expression has no idea what it is because it's an anonymous type. So why not just use var?
  Func<User, var>
Seems easy enough. I don't have to know the type because of var right? Wellll problem is the compiler is looking at the lambda expression to figure out what var will be. Mr. Lambda expression can't really figure out the type either. Enter the wall. Currently there is no way around this without methods or classes created. Supposedly there are things called Mumble Types on the way that will solve this problem.

Wednesday, July 9, 2008

Joining By Anonymous Types

Just found this out yesterday so I thought I would post and pass on to all two of you reading this. Suppose you have a User table and a Contacts table and you wanted to find all the users that match up with the contacts table. Now suppose there is no direct correlation. What to do? You could do something really brilliant by joining the tables together on FirstName and LastName, because we all know that there will always only be one John Smith in either table. Screw you, I couldn't think of a better example at the time.
public static List<User> GetAllUsersWithMatchingContactInformationUsingJoin()
{
  List<User> foundUsers;
          
  var query = from user in dataContext.Users
              join contact in dataContext.Contacts on new {user.FirstName, user.LastName } equals new { contact.FirstName, contact.LastName }
              select user;
          
              foundUsers = query.ToList();
          
  return foundUsers;
}
As you can see here:
join contact in dataContext.Contacts on new {user.FirstName, user.LastName } equals new { contact.FirstName, contact.LastName }
You can create a type on the fly and then compare it to another. I thought that was interesting.