Binding anonymous type to create BindingList

I am trying to create a BindingList <> from an anonymous type returned by a LINQ query, but a BindingList <> does not accept an anonymous type, the 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);

The last line is a general argument, what to place ???

+4
source share
3 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 as follows:

        var query = entities
            .Select(e => new
            {
               // construct anonymous entity here
            })
            .ToList()
            .ToBindingList();
+5
source

If you need to use this object in other places, I would suggest either using it dynamic, or even better just creating the desired object as struct.

public class RechargeLogData
{
    public int Id { get; set; }
    public string Company { get; set; }
    public string SubscriptionNo { get; set; }
    public string Amount { get; set; }
    public string Time { get; set; }
}

var data = context.RechargeLogs.Where(t => t.Time >= DateTime.Today).
       Select(t => new RechargeLogData()
       {
            Id = t.Id,
            Company = t.Compnay,
            SubscriptionNo = t.SubscriptionNo,
            Amount = t.Amount,
            Time = t.Time
       });

var tmp =  new BindingList<RechargeLogData>(data);
+1
source

, . , , .

var tmp =  new BindingList<object>(data);
-1

Source: https://habr.com/ru/post/1544854/


All Articles