Why do I need to call the Cast <> method of an extension in a DataGridViewRow?

This does not work.

 var result = from row in grid.Rows where (string) row.Cells["COLUMN_1"].Value == "Test" select row.Cells["COLUMN_2"].Value as int?; 

But it is so.

 var result = from row in grid.Rows.Cast<DataGridViewRow>() where (string) row.Cells["COLUMN_1"].Value == "Test" select row.Cells["COLUMN_2"].Value as int?; 

As far as I can tell, a DataGridViewRowCollection is a collection of DataGridViewRows. So, why should I pass each member to a DataGridViewRow before I can access its properties?

Does this have anything to do with the fact that the DataGridViewRowCollection implements a non-generic IEnumerable , but not a generic IEnumerable<DataGridViewRow> ? Or that he apparently uses an ArrayList inside? This does not cause me any real problems, but I would like to better understand this.

+1
source share
1 answer

Yes, this is precisely because of the interface that it advertises. Almost all extension methods in LINQ work on IEnumerable<T> , not IEnumerable . Cast<> is one way to bridge this gap - OfType<> is different.

However, there is an easier way to call Cast<T> - just explicitly enter a range variable:

 var result = from DataGridViewRow row in grid.Rows where (string) row.Cells["COLUMN_1"].Value == "Test" select row.Cells["COLUMN_2"].Value as int?; 

The compiler turns this into exactly the same code as your second sample.

+6
source

Source: https://habr.com/ru/post/1395421/


All Articles