Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to use CopyTo to get a custom collection into an enumerable?

Consider the following code:

var results = searcher.FindAll();

SearchResult[] srList = new SearchResult[results.Count];
results.CopyTo(srList, 0);

where searcher.FindAll() returns a System.DirectoryServices.SearchResultCollection.

Do I have to use the CopyTo to get them into an enumerable that I can then later use in a Parallel.ForEach? And if so, why?

I have using System.Linq but there isn't a ToList method popping up.

Thanks all!

like image 254
Mike Perrenoud Avatar asked Nov 25 '25 14:11

Mike Perrenoud


2 Answers

You can use Cast<T>() to cast a SearchResultCollection to IEnumerable<T>, and ToArray<T>() to create an array.

SearchResult[] results = searcher.FindAll().Cast<SearchResult>().ToArray();

Make sure you include the System.Linq namespace:

using System.Linq;
like image 71
jrummell Avatar answered Nov 27 '25 03:11

jrummell


You can use the Cast<T> extension method to go from a non-generic IEnumerable to an IEnumerable<SearchResult>:

var results = searcher.FindAll().Cast<SearchResult>();
like image 27
D Stanley Avatar answered Nov 27 '25 04:11

D Stanley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!