el ninho
el ninho

Reputation: 4233

Skip items of a specific type in foreach loop

I have this code for filling 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 problem when cell is not same datatype as I set in table.

How to skip cell which is wrong datatype?

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

foreach //...
{
    if //if datatype is not right
    {
        continue;
    }
}

Upvotes: 11

Views: 4897

Answers (3)

sll
sll

Reputation: 62484

You can use LINQ OfType<IMyType>() method to filter out wrong items:

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

MSDN:

Filters the elements of an IEnumerable based on a specified type. The OfType(IEnumerable) method returns only those elements in source that can be cast to type TResult

Upvotes: 11

Oded
Oded

Reputation: 498942

Use the is operator:

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

is:

Checks if an object is compatible with a given type.

Upvotes: 4

TJHeuvel
TJHeuvel

Reputation: 12608

C# has an is operator.

For example:

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

Upvotes: 8

Related Questions