How to Casting DataSource to List<T>?

那年仲夏 提交于 2019-12-01 15:08:25

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();

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

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

Cristhian Boujon

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!