Reputation: 490
I am trying to convert ICollection to List using below code-
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
Message = Parameter count mismatch.
How to convert ICollection to List?
Upvotes: 33
Views: 74739
Reputation: 3356
the easiest way to do that for me was the following:
var array = Array.Empty<string>();
parameters.Keys.CopyTo(array, 0);
Upvotes: 0
Reputation: 1585
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?
I am working with two different types.
In my case both share the same underlying classes (Integrations are fun I guess).
PLAY - https://dotnetfiddle.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?
Upvotes: 0
Reputation: 908
Because ICollection implement IEnumerable you can use a foreach.
foreach(var item in list_Stuctures)
{
lst_DataStructure.ADD(item);
}
Upvotes: -2
Reputation: 26436
You can supply the collection as an argument in the List<T>
constructor:
List<DataStructure> lst_DataStructure = new List<DataStructure>(list_Stuctures);
Or use the .ToList()
extension method, which does exactly the same thing.
Upvotes: 6
Reputation: 11389
The easiest way to convert a ICollection
to a List
is the usage of LINQ like (MSDN)
List<T> L = C.ToList();
Dont't forget to add
using System.Linq;
otherwise ToList()
is not available.
Upvotes: 76