The
declaration for the Cast operator is given as follows:
public static IEnumerable
Cast
(
IEnumerable source
)
Now let us consider an array list containing objects of type Item, which we have
seen in our previous examples. The ArrayList operator does not implement
IEnumerable. We can use the Cast operator to change the type of the result.
ArrayList stringsOne = new ArrayList
{
new Item
{
Category = "Icecreams", Name = "Chocolate Fudge Icecream",
Ingredients = "cream, milk, mono and diglycerides...",
Cholesterol = "50mg", Protein = "4g", TotalCarbohydrates = "35g",
TotalFat = "20g", Price = 10.5,
FatContents = new FatContent
{
SaturatedFat = "6g", TransFat = "4g", OtherFat = "6g"
}
Chapter 7
[ 193 ]
}
};
IEnumerable- icecreamsList = stringsOne.Cast
- ().
Where(o => o.Category == "Icecreams");
ArgumentNullException is raised if the source is null. If the source element cannot
be cast to the type specified, InvalidCastException will be thrown.
OfType
The OfType operator is used to filter elements based on a particular type.
Pages:
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291