简体   繁体   English

转换 ICollection<t> 列出<t></t></t>

[英]Convert ICollection<T> to List<T>

I am trying to convert ICollection to List using below code-我正在尝试使用以下代码将 ICollection 转换为 List-

ICollection<DataStructure> list_Stuctures = dataConnectorService.ListStructures(dataConnector, SupportedDataStructures.All);

List<DataStructure> lst_DataStructure = new List<DataStructure>();

list_Stuctures.CopyTo(lst_DataStructure);

On last line, I get below exception-在最后一行,我得到以下异常 -

Exception = TargetParameterCountException异常 = TargetParameterCountException

Message = Parameter count mismatch.消息 = 参数计数不匹配。

How to convert ICollection to List?如何将 ICollection 转换为列表?

The easiest way to convert a ICollection to a List is the usage of LINQ like ( MSDN ) ICollection转换为List的最简单方法是使用LINQ like( MSDN

List<T> L = C.ToList();

Dont't forget to add 不要忘记添加

using System.Linq;

otherwise ToList() is not available. 否则, ToList()不可用。

You can supply the collection as an argument in the List<T> constructor: 您可以在List<T>构造函数中将集合作为参数提供:

List<DataStructure> lst_DataStructure = new List<DataStructure>(list_Stuctures);

Or use the .ToList() extension method, which does exactly the same thing. 或使用.ToList()扩展方法,其作用完全相同。

保持简单, ToList

List<DataStructure> lst_DataStructure = list_Stuctures.ToList();

Because ICollection implement IEnumerable you can use a foreach. 因为ICollection实现IEnumerable,所以可以使用foreach。

foreach(var item in list_Stuctures) 
{
  lst_DataStructure.ADD(item);
}

None of the recommendations worked for me.这些建议都不适合我。 I'm a bit surprised to not see this pretty obvious answer.我有点惊讶没有看到这个非常明显的答案。 At least it seems obvious to me after looking through other attempts.至少在看过其他尝试后,这对我来说似乎很明显。 This may be a tab bit longer in some cases, but perhaps worth it for performance and peace of mind?在某些情况下,这可能会长一点,但为了性能和安心,也许值得吗?

What do you guys think?你们有什么感想?

For context对于上下文

I am working with two different types.我正在使用两种不同的类型。

In my case both share the same underlying classes (Integrations are fun I guess).在我的例子中,两者共享相同的底层类(我猜集成很有趣)。

PLAY - https://do.netfiddle.net/oTa4Dt#玩 - https://do.netfiddle.net/oTa4Dt#

/// One is ---------- | ---- ICollection<T>
/// The other is ---- | ---- List<PreferencesResponse>

ICollection<T> result = default!;

var myPreferences = new List<PreferencesResponse>();
foreach (var preference in result.Result.ToList())
{
    var preferencesResponse = new PreferencesResponse()
    {
        Id = preference.Id,
        Status = preference.Status,
        StatusDescription = preference.StatusDescription,
        Priority = preference.Priority
    };
    mySupplierPreferences.Add(preferencesResponse);
}
returnValue = new Response(true, mySupplierPreferences);

Are there any reasons you can think of that this wouldn't be correct or at least - most correct?您是否有任何理由认为这不正确或至少 - 最正确?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM