hi, I'm just learning C# after being a Delphi coder for waayyy to long :D I was wondering, why isn't it possible to use an else statement with the foreach statement? Check out my quick and dirty demo code:
namespace ConsoleApplication
{
class Product
{
public string Code { get; set; }
public string Description { get; set; }
}
class Program
{
static void Main(string\[\] args)
{
//create some enumerable list
IEnumerable<Product> myProductList = new List<Product>
{
new Product() {Code = "CDR", Description = "CD-Rom"},
new Product() {Code = "DVD", Description = "DVD-Rom"},
new Product() {Code = "BRD", Description = "BlueRay Disc"},
};
//select some products with LINQ
var myProductSelection = (from aProduct in myProductList where aProduct.Code.StartsWith("R") select aProduct);
//Print header text
Console.WriteLine("The products that were found:");
//loop through products in selection
foreach (var aProduct in myProductSelection)
{
Console.WriteLine("Found product: " + aProduct.Code);
}
//pause to check results
Console.ReadKey();
}
}
}
The above code returns nothing, since none of the product codes start with a "R". Would be nice if I could do this when my result is empty:
//Print header text
Console.WriteLine("The products that were found:");
//loop through products in selection
foreach (var aProduct in myProductSelection)
{
Console.WriteLine("Found product: " + aProduct.Code);
}
else
{
Console.WriteLine("No products were found!");
}
Just some ranting.. any good solutions to this unlike something like this?
//Print header text
Console.WriteLine("The products that were found:");
int x = 0;
//loop through products in selection
foreach (var aProduct in myProductSelection)
{
x++;
Console.WriteLine("Found product: " + aProduct.Code);
}
if (x > 0)
Console.WriteLine("No products were found!");
thx for any suggestions offered :)
- Life would be so much easier if I had the source code! - If C#