Skip elements of a specific type in a foreach loop

I have this code to populate datatable from excel file:

for (int rowIndex = cells.FirstRowIndex; rowIndex <= cells.LastRowIndex; rowIndex++) { var values = new List<string>(); foreach (var cell in cells.GetRow(rowIndex)) { values.Add(cell.Value.StringValue); } dataTable.LoadDataRow(values.ToArray(), true); } 

I have a problem when the cell is not the same data type as the table.

How to skip a cell that is the wrong data type?

I also know this, but I can't get it to work in my case:

 foreach //... { if //if datatype is not right { continue; } } 
+8
c # loops foreach
source share
3 answers

You can use the LINQ OfType<IMyType>() method to filter out invalid elements:

 // do not forget adding using System.Linq; var filteredItems = items.OfType<IMyType>(); var values = new List<IMyType>(filteredItems); 

MSDN :

Filters IEnumerable elements based on the specified type. The OfType (IEnumerable) method returns only those elements to the source that can be superimposed on the TResult type

+9
source share

C # has an operator.

For example:

 foreach(var item in collection) { if(item is string) { //Do something with the string. } } 
+8
source share

Use the is statement:

 if(cell is MyType) { // can work } 

is :

Checks if an object is compatible with this type.

+4
source share

All Articles