How to use Cast of C #
This article mainly explains "how to use Cast in C#". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use Cast in C#.
There is a List control (ASP.Net) and a ListView control (WinForm) in the form control.
Take ListView as an example. The ListView control can contain many items, or it can be said to be a collection. Let's take a look at its Items property.
Public class ListView: Control {public ListView.ListViewItemCollection Items {get;} public class ListViewItemCollection: IList, ICollection, IEnumerable {}}
The Items type of ListView is ListView.ListViewItemCollection, and this ListViewItemCollection implements IEnumerable. ListView.Items is a collection of non-generics, so you can apply Cast. The following code assumes that listBox data is bound to a collection of Employee:
Int count = listBox.Items.Cast () .Count (); bool b = listBox.Items.Cast () .Any (e = > e.FirstName = = "Bob")
Similarly, C # Cast can be used on ComboBox, DataGridView, and TreeNode:
/ / ComboBox var v1 = comboBox.Items.Cast (); / / DataGridView var v2 = dataGridView.SelectedRows.Cast (); var v3 = dataGridView.SelectedColumns.Cast (); var v4 = dataGridView.SelectedCells.Cast (); / / TreeNode var v5 = treeNode.Nodes.Cast ()
Line 4 should be the most frequently used of these applications, and getting selected rows is one of the most frequently used operations in DataGridView. Consider the following code:
/ / calculate the average age
Int age = dataGridView.SelectedRows.
Cast () .Average (p = > p.Age)
/ / the city where the statistics are located
String [] cities = dataGridView.SelectedRows.
Cast (). Select (p = > p.City). Distinct ()
Using C # Cast, our code is very concise. Cast can even be used on the base class Control of all controls, and its Controls property is also non-generic!
/ / Control var V6 = control.Controls.Cast (); thank you for reading, the above is the content of "how to use the Cast of C#", after the study of this article, I believe you have a deeper understanding of how to use the Cast of C#, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!