Saturday, March 14, 2009

Working on collections and searching for objects

I am reading a book about F# which is a functional language for .net. At the same time I have been introduced to JQuery which is a javascript framework for querying and manipulating objects on a html page. It has sprung some ideas for the plain framework.

What I'm striving for is the possibility to query an object structure for objects. When the objects are returned, it should be possible to perform actions on all these objects in one statement. LINQ might be usefull for querying but at the moment I'm guessing that it won't fulfill my needs.

Lets me give an example of what is currently in progress. This will find all TextBox objects that contain the value '0' and set the background colour on it:

form.find<textbox>("[.Text='0']").Do(t=>t.BackColor= Color.Azure);


The .find method is an extension method on object, which means you can use it for any object. The .Do method is an extension method to all IEnumerable<> that lets you perform the lambda function on all instances contained in the list.

Another example is by using the Map method.

IList<string> textboxValues = form.find<textbox>().Map<string>(t=>x.Name +": " + x.Text);

This will produce a list of strings with that name and value of all textboxes somewhere on the form. The Map method is currently not an extension method as I haven't figured out how to implement the syntax of just just providing one generic parameter to an extension method working on a generic type :(
Actually there is a Map extension method, but it requires you to provide the generic type of the collection as well. In this case it would be .Map<textbox,string>(...)

The one thing that is missing is the syntax to search for objects. Will it be LINQ or will it be a homegrown dsl?

If you want to use the .Do method here it is:


public delegate void OneParemeterNoReturn(T x);
public static void Do<t>(this IEnumerable<t> o,OneParemeterNoReturn<t> func){
foreach(T t in o){
func.Invoke(t);
}
}


otherwise you can wait for it to apear in the plain framework :)

2 comments:

  1. It turns out that .Net can detect the output type of your lambda expression and provide the right generic type.

    .Map(t => x.Name + ": " + x.Text) will be valid. If you try to put it in a variable that isn't IList<string> it won't compile as the return type of the lambda i string.

    ReplyDelete
  2. oh, and .Net already comes with a single parameter input delegate. I present...: Action<T>

    ReplyDelete