How to Casting DataSource to List?

后端 未结 4 1502
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-17 11:11

I have the following method that load products on a DataGridView

private void LoadProducts(List products)
{
    Source.DataSource = products;          


        
相关标签:
4条回答
  • 2021-01-17 11:23

    Convining the answers This is my solution:

    private void SaveAll()
    {
        Repository repository = Repository.Instance;
        List<Product> products = (List<Product>)Source.DataSource;
        IEnumerable<object> objects = products.Cast<object>();
        repository.SaveAll<Product>(objects.ToList<object>());
        notificacionLbl.Visible = false;
    }
    

    I accept constructive criticisms.

    0 讨论(0)
  • 2021-01-17 11:26

    You can't cast covariantly directly to List;

    Either:

    List<Product> products = (List<Product>)Source.DataSource;
    

    or:

    List<Object> products = ((List<Product>)Source.DataSource).Cast<object>().ToList();
    
    0 讨论(0)
  • 2021-01-17 11:27

    Your List ist of type List<Product> which is different from List<object>. Try to cast to List<Product>

    0 讨论(0)
  • 2021-01-17 11:40

    So how can I cast the DataSource to an List?

    You have plenty of options

    var products = (List<Product>)Source.DataSource; // products if of type List<Product>
    

    or

     List<Object> products = ((IEnumerable)Source.DataSource).Cast<object>().ToList();
    

    or

    List<Object>  products = ((IEnumerable)Source.DataSource).OfType<object>().ToList();
    

    or

    List<Object> products = new List<Object>();
    ((IEnumerable)Source.DataSource).AsEnumerable().ToList().ForEach( x => products.Add( (object)x));
    
    0 讨论(0)
提交回复
热议问题