This
operator can be used along with the Cast operator to cast the element of a particular
type, so that we can avoid InvalidcastException.
Following is an array list which contains mixed types of elements. It has strings,
integer and double. Out of these values, if we want to extract only the elements that
are strings, then we can use the OfType operator as given below.
ArrayList strings = new ArrayList(5);
strings.Add("Icecreams");
strings.Add("Chocolates");
strings.Add("Pastries");
strings.Add(5);
strings.Add(2.5);
IEnumerable
onlyStrings = strings.OfType();
Console.WriteLine("The Elements of type string are :");
foreach (string str in onlyStrings)
Console.WriteLine(str);
We will get the ArgumentNullException if the source value is null.
ToArray
The ToArray operator is used for converting a collection into an array. The
declaration for the ToArray operator is as follows:
public static TSource[] ToArray
(
IEnumerable source
)
This operator enumerates the sequence and returns the elements in the form of an
array.
Pages:
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292