I have foreach to show the result from myquery, it works when the result isnt null. and I want to know does the foreach have else? to take action when the result from myquery is null?
var rs = from cs in db.CsCustomers from ai in db.ArInvoices where cs.CustomerID == ai.CustomerID && ai.Kategori != null orderby cs.Unit select new { cs.CustomerID, cs.Unit, cs.Name }; foreach (var r in rs) { c = new TableCell(); c.Text = r.CustomerID; c.RowSpan = jk; tr.Cells.Add(c); c = new TableCell(); c.Text = r.Unit; c.RowSpan = jk; tr.Cells.Add(c); c = new TableCell(); c.Text = r.Name; c.RowSpan = jk; tr.Cells.Add(c); } 35 Answers
Why not to put check first -
if(rs == null) {} else { foreach..... } Maybe you will need this. Anyway, in case you often need default behavior for empty lists, you may create next extension method.
void Main() { var elements = Enumerable.Range(0,20); elements.ForEachWithElse(x=>Console.WriteLine (x), ()=>Console.WriteLine ("no elements at all")); elements.Take(0).ForEachWithElse(x=>Console.WriteLine (x), ()=>Console.WriteLine ("no elements at all")); } public static class MyExtensions { public static void ForEachWithDefault<T>(this IEnumerable<T> values, Action<T> function, Action emptyBehaviour) { if(values.Any()) values.ToList().ForEach(function); else emptyBehaviour(); } } No it does not have an else operator. You could wrap it in an if else
var rs = from cs in db.CsCustomers from ai in db.ArInvoices where cs.CustomerID == ai.CustomerID && ai.Kategori != null orderby cs.Unit select new { cs.CustomerID, cs.Unit, cs.Name }; if(rs != null && rs.Any()) //for the .Count you have to add using System.Linq; foreach (var r in rs) { c = new TableCell(); c.Text = r.CustomerID; c.RowSpan = jk; tr.Cells.Add(c); c = new TableCell(); c.Text = r.Unit; c.RowSpan = jk; tr.Cells.Add(c); c = new TableCell(); c.Text = r.Name; c.RowSpan = jk; tr.Cells.Add(c); } }else{ //the else part } 1No, there's no foreach-else loop... If you need that functionality, either use a different type of loop (for-loop or maybe do-while-loop) or test for number of elements first.
Here is an article on how to implement something along the lines.
It's your regular every day foreach on IEnumerable but allows you to specify both a "loop-action" and an "else-action" where the latter is executed after the loop unless you break the loop by returning false from the former. It's a tad clumsier than Python but still useful
What you can do instead is to just check it being null/empty with an if test, and then do something in the else part. However, when doing DB stuff, it's better to return an empty list when there are no result, instead of returning null.