C# - 将类型数组转换为泛型列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1096734/
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
C# - Convert a Type Array to a Generic List
提问by
Code Snippet:
代码片段:
ShippingPeriod[] arrShippingPeriods;
.
.
.
List<ShippingPeriod> shippingPeriods = ShippingPeriodList.ToList<ShippingPeriod>();
The Last line won't compile and the error I get is:
最后一行不会编译,我得到的错误是:
"'ShippingPeriod[]' does not contain a definition for 'ToList' and the best extension method overload 'System.Linq.Enumerable.ToList(System.Collections.Generic.IEnumerable)' has some invalid arguments"
“'ShippingPeriod[]' 不包含'ToList' 的定义,并且最好的扩展方法重载'System.Linq.Enumerable.ToList(System.Collections.Generic.IEnumerable)'有一些无效的参数”
采纳答案by TheVillageIdiot
try this:
尝试这个:
ShippingPeriod [] arrShippingPeriods;
//init and populate array
IList<ShippingPeriods> lstShippingPeriods =
arrShippingPeriods.ToList<ShippingPeriods>();
You need to call ToListon the array object not the class of objects contained in array.
您需要在数组对象上调用ToList而不是数组中包含的对象类。
回答by Valentin Vasilyev
Another option would be:
另一种选择是:
ShippingPeriod [] arrShippingPeriods;
var lstShippingPerios=new List<ShippingPeriod>(arrShippingPeriods);
Since arrays already implement IEnumerable, you can pass it to the List constructor.
由于数组已经实现了 IEnumerable,您可以将其传递给 List 构造函数。
Hope this helps
希望这可以帮助
回答by Jon Skeet
As others have said, you need to call ToList
on your array. You haven't shown what ShippingPeriodList
is.
正如其他人所说,您需要调用ToList
您的数组。你还没有显示是什么ShippingPeriodList
。
However, when you get that bit right, note that you won't need to provide the type argument, as type inference will do it for you. In other words, this should work fine:
但是,当您正确理解这一点时,请注意您不需要提供类型参数,因为类型推断会为您完成。换句话说,这应该可以正常工作:
List<ShippingPeriod> list = arrShippingPeriods.ToList();
回答by Juan
I got the solution!!!
我得到了解决方案!!!
You have to put "using System.Linq;" in the header of your Class, and that′s it. When you put that, the array recognizes toList() command.
你必须把“使用 System.Linq;” 在你的类的标题中,就是这样。当您放置它时,数组会识别 toList() 命令。