Enumerable. Cast <T> is used to convert IEnumerable to a generic version of IEnumerable <T>. After conversion, you can enjoy other Enumerable methods (such as Where and Select), which greatly facilitates our coding.
However, only one example of converting ArrayList is provided in MSDN. Many people have seen that List <T> is being used now. Who else will use ArrayList or Cast <T> is of little use, unless you are dealing with some of the Code left behind.
In fact, Cast <T> is not so simple. It can be used in many places.
Let's take a look at the example in MSDN: This example is simple and easy to understand.
The other collection classes in. Net 1.x can also be used as above, such as Array and non-generic List...
Interrupt. Is there a List of non-generic versions? I have never used. Net 1.x, but it is not clear, but the form control contains a List control (ASP. Net) and a ListView control (WinForm ).
Take ListView as an example. The ListView control can contain many Items or a set. Let's take a look at its Items attributes!
1 System. Collections. ArrayList fruits = new System. Collections. ArrayList ();
2 fruits. Add ("apple ");
3 fruits. Add ("mango ");
4
5 IEnumerable <string> query = fruits. Cast <string> ();
6 foreach (string fruit in query) Console. WriteLine (fruit );
1 public class ListView: Control
2 {
3
4 public ListView. ListViewItemCollection Items {get ;}
5
6 public class ListViewItemCollection: IList, ICollection, IEnumerable {}
7
8}
The Items type of ListView is ListView. ListViewItemCollection, which implements IEnumerable.
ListView. Items is a non-generic set, so you can apply Cast <T>.
The following code assumes that the listBox data is bound to a set of employees:
1 int count = listBox. Items. Cast <Employee> (). Count ();
2 bool B = listBox. Items. Cast <Employee> (). Any (e => e. FirstName = "Bob ");
(Of course, if there is a reference to the set of Employee, no Cast is needed. Here is just an example)
Similarly, Cast <T> can be used on ComboBox, DataGridView, and TreeNode:
1 // ComboBox
2 var v1 = comboBox. Items. Cast <People> ();
3