C# 如何将数据源转换为 List<T>?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14279977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:18:14  来源:igfitidea点击:

How to Casting DataSource to List<T>?

c#winformsdatagridviewcastingdatasource

提问by Cristhian Boujon

I have the following method that load products on a DataGridView

我有以下方法可以在 DataGridView 上加载产品

private void LoadProducts(List<Product> products)
{
    Source.DataSource = products;  // Source is BindingSource
    ProductsDataGrid.DataSource = Source;
}

And now I'm trying to give me back to save them as shows below.

现在我试图让我回来保存它们,如下所示。

private void SaveAll()
{
   Repository repository = Repository.Instance;
   List<object> products = (List<object>)Source.DataSource; 
   Console.WriteLine("Este es el número {0}", products.Count);
   repository.SaveAll<Product>(products);
   notificacionLbl.Visible = false;
}

But I get an InvalidCastExceptionon this line:

但我InvalidCastException在这条线上得到了一个:

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

So how can I cast the DataSource to an List?

那么如何将 DataSource 转换为 List 呢?

采纳答案by Dave Bish

You can't cast covariantly directly to List;

您不能直接将协变转换为 List;

Either:

任何一个:

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

or:

或者:

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

回答by CubeSchrauber

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

您的 List 类型List<Product>不同于List<object>. 尝试投射到List<Product>

回答by Tilak

So how can I cast the DataSource to an List?

那么如何将 DataSource 转换为 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));

回答by 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.

我接受建设性的批评。