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 ???
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 .
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With