'Convert ICollection<T> to List<T>
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?
Solution 1:[1]
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.
Solution 2:[2]
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.
Solution 3:[3]
Keep it simple, ToList:
List<DataStructure> lst_DataStructure = list_Stuctures.ToList();
Solution 4:[4]
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://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?
Solution 5:[5]
Because ICollection implement IEnumerable you can use a foreach.
foreach(var item in list_Stuctures)
{
lst_DataStructure.ADD(item);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Fruchtzwerg |
| Solution 2 | C.Evenhuis |
| Solution 3 | Amit |
| Solution 4 | Urasquirrel |
| Solution 5 | Zohar Chiprut |
