Q:

Conditions in LINQ expression C#

I'm a beginner with LINQ. I'm trying to create a CSV file using a LINQ Expression I found on Stack Overflow : 
var sb = new StringBuilder();

var headers = dgvDonnees.Columns.Cast<DataGridViewColumn>();
sb.AppendLine(string.Join(",", headers.Select(column => "\"" + column.HeaderText + "\"").ToArray()));

foreach (DataGridViewRow row in dgvDonnees.Rows)
{
    var cells = row.Cells.Cast<DataGridViewCell>();
    sb.AppendLine(string.Join(",", cells.Select(cell => "\"" + cell.Value + "\"").ToArray()));
}

I want to add this simple condition to the foreach loop : (I use this condition in a for loop)
if (Convert.ToInt32(dgvDonnees.Rows[i].Cells[10].Value) == 0) continue;

I want the lines whose 10th cell is not zero is present in the final CSV.
How can I do this? Thank you.

A:

If you actually want a LINQ solution, as your question implies, you will want to do this:
foreach (DataGridViewRow row in dgvDonnees.Rows
    .Where(r => Convert.ToInt32(r.Cells[10].Value) != 0))
{
    var cells = row.Cells.Cast<DataGridViewCell>();
    sb.AppendLine(string.Join(",", cells.Select(cell => "\"" + cell.Value + "\"").ToArray()));
}

In other words, let LINQ do the filtering for you instead of adding extra statements to the loop body. It's more concise, and more correctly reflects the semantics you are looking for (i.e. the code looks a lot more like your specification "I want the lines whose 10th cell is not zero", whereas using continue in the loop requires an inverted logic expression from what the specification actually is).

A:

Just put at the beginning of your foreach loop this line :
if (Convert.ToInt32(row.Cells[10].Value) == 0) continue;

row replace your dgDonnees.Rows[i]
Finally you will have this code:
foreach (DataGridViewRow row in dgvDonnees.Rows)
{
    if (Convert.ToInt32(row.Cells[10].Value) == 0) continue;

    var cells = row.Cells.Cast<DataGridViewCell>();
    sb.AppendLine(string.Join(",", cells.Select(cell => "\"" + cell.Value + "\"").ToArray()));
}

