Friday, April 29, 2011

Creating anonymous types based on lambda expression

Hi,

I'm trying to create a Fluent Interface to the Winforms Datagrid. This should allow me to use a typed datasource and easy use of properties of properties (Order.Custom.FullName)

I'm adding the columns on initialization and trying to set the property to use there:

dgv.With<Order>().Column("Client Name").On(x => x.Client.FullName);

The original question then poses itself when setting the Datasource:

dgv.SetTypedDatasource<T>(IList<Order> orders)

A big problem here is that Generic Controls are not possible (I guess), so that T cannot be specified for the class, but has to be specified per method...

I want to create a list of anonymous types, based on a given property in a lambda expression:

something like:

ProcessList<Client>(clientList, x => x.FullName);

Is it possible to do something like this:

[Edit] Note that in practice, the expressions will be set earlier, and will be fetched elsewhere...

public void ProcessList<T>(IList<T> sourceList, Expression<Func<T, object>> expression)
{
    var list =
        (from T x
         in sourceList
         select new { expression })
         .ToList();

    // process list ....  grid.DataSource = list;
}

So, I would like to create anonymous types based on the given expression. I know I can evaluate that expression to retrieve the correct properties.

I'm kinda stuck, is something like this possible?

Any ideas?

From stackoverflow
  • Well, with a simple call to Select you can come very close:

    ProcessList(clientList.Select(x => new { x.FullName }));
    
    ...
    
    public void ProcessList<T>(IEnumerable<T> list)
    {
        // process list ... T will be an anonymous type by now
        grid.DataSource = list;
    }
    

    (That assumes you don't need the original list in ProcessList as well. If you do, move the select into there.)

    Bertvan : so true, I was getting it all wrong...
    Marc Gravell : Note that if that is a winform grid, it will need a ToList() - webform grids are happy with IEnumerable, though.
    Bertvan : Still, not quite what I need, I'll explain a bit more in the question.
    Bertvan : @Marc, yes I forgot that line :)
  • isn't that just grid.DataSource = sourceList.AsQueryable().Select(expression).ToList();

    Note that it would be better to introduce a second generic, such that the list is typed:

        public static void ProcessList<TSource, TValue>(
            IList<TSource> sourceList,
            Func<TSource, TValue> expression)
        {
            grid.DataSource = sourceList.Select(expression).ToList();
        }
    

    Note I switched from Expression<...> to just Func<...>, as it seemed to serve no purpose.

0 comments:

Post a Comment