Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding anonymous type to Create a BindingList

Tags:

c#

generics

I am trying to create a BindingList<> from anonymous type returned by LINQ query but BindingList<> do not accept anonymous type, following is my code

var data = context.RechargeLogs.Where(t => t.Time >= DateTime.Today).
           Select(t => new 
           {
                col1 = t.Id,
                col2 = t.Compnay,
                col3 = t.SubscriptionNo,
                col4 = t.Amount,
                col5 = t.Time
           });

var tmp =  new BindingList<???>(data);

In the last line generic argument what to place ???

like image 361
Sukhdevsinh Zala Avatar asked Jun 17 '14 06:06

Sukhdevsinh Zala


People also ask

How do you declare an anonymous type?

You create anonymous types by using the new operator together with an object initializer. For more information about object initializers, see Object and Collection Initializers. The following example shows an anonymous type that is initialized with two properties named Amount and Message .

When can an anonymous type be created?

In C#, you are allowed to create an anonymous type object with a new keyword without its class definition and var is used to hold the reference of the anonymous types. As shown in the below example, anony_object is an anonymous type object which contains three properties that are s_id, s_name, language.

What is anonymous type in LINQ?

Anonymous types provide a convenient way to encapsulate a set of read-only properties in an object without having to explicitly define a type first. If you write a query that creates an object of an anonymous type in the select clause, the query returns an IEnumerable of the type.

What is BindingList in C#?

BindingList is a generic list type that has additional binding support. While you can bind to a generic list, BindingList provides additional control over list items, i.e. if they can be edited, removed or added. BindingList also surfaces events that notify when the list has been changed.


1 Answers

You can write an extension method:

static class MyExtensions
{
    public static BindingList<T> ToBindingList<T>(this IList<T> source)
    {
        return new BindingList<T>(source);
    }
}

and use it like this:

        var query = entities
            .Select(e => new
            {
               // construct anonymous entity here
            })
            .ToList()
            .ToBindingList();
like image 93
Dennis Avatar answered Sep 23 '22 03:09

Dennis