2

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?

1
  • I am not quite sure, what do you want in your anonymous type ? Commented Apr 16, 2009 at 20:28

2 Answers 2

4

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.)

Sign up to request clarification or add additional context in comments.

3 Comments

Note that if that is a winform grid, it will need a ToList() - webform grids are happy with IEnumerable, though.
Still, not quite what I need, I'll explain a bit more in the question.
@Marc, yes I forgot that line :)
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.