Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
}
like image 869
el ninho Avatar asked Jan 26 '12 09:01

el ninho


People also ask

How do you skip elements in foreach loop?

if want to skipped some index then make an array with skipped index and check by in_array function inside the foreach loop if match then it will be skip.

How do you continue foreach?

Use return For practical purposes, return in a forEach() callback is equivalent to continue in a conventional for loop. When you return , you skip the rest of the forEach() callback and JavaScript goes on to the next iteration of the loop.

Does foreach generate garbage?

In order for the foreach loop to not create any garbage, you need to use a List<T> variable. You can't use an interface that it implements like IEnumerable<T> or 40 bytes of garbage will be created every loop. Normally you can avoid that though, and you should if you want to take advantage of a garbage-free foreach .


1 Answers

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

like image 166
sll Avatar answered Oct 02 '22 18:10

sll