beginner question: foreach .. else?
-
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#
-
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#
Ted On The Net wrote:
Just some ranting.. any good solutions to this unlike something like this?
I can only think of 1 fundamentally different solution - explicitly test for the number of items in myProductSelection. Personally I would set a bool to true in the foreach rather than counting the iterations, but that is not that much different from the solution you gave. There is no build-in way to do this, as far as I know.
-
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#
does myProductSelection have a count or a length? Most strucutres that implement IEnumerable do. If so just check to see if the count is greater than zero.
-
does myProductSelection have a count or a length? Most strucutres that implement IEnumerable do. If so just check to see if the count is greater than zero.
yes, it does. One could implement it like this:
if (myProductSelection.Count() != 0)
{
//loop through products in selection
foreach (var aProduct in myProductSelection)
{
Console.WriteLine("Found product:" + aProduct.Code);
}
}
else
{
Console.WriteLine("No products found!");
}But why should I? If the foreach loop doesn't get executed, I know I've got the same result as if I used the above if-statement. So imo this gives me redundant code. Or do you disagree?
- Life would be so much easier if I had the source code! - If C# had true garbage collection, most applications would delete themselves upon execution ;)
-
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#
I understand why you want this, but there is no implicit way of doing it. But, think that using foreach is a replacement for getting the enumerator, calling while(enumerator.MoveNext()) and setting a variable to enumerator.Current. (and at the end calling Dispose, if possible). So, the best solution for this is doing something like:
using(var enumerator = enumerable.GetEnumerator())
{
if (enumerator.MoveNext())
{
do
{
var someVariable = enumerator.Current;... the loop code... } while(enumerator.MoveNext());
}
else
{
... the else you want ...
}
}And you can even create a method using delegates Action<T> for the value and non-generic Action for the else. Something like:
ForEachOrElse(IEnumerable<T> enumerable, Action<T> actionForEachValue, action elseAction)
And to use it you call something like:
ForEachOrElse
(
enumerable,
(value) =>
{
... the code for each value...
},
() =>
{
... the code for else ...
}
);modified on Tuesday, March 9, 2010 9:34 AM
-
I understand why you want this, but there is no implicit way of doing it. But, think that using foreach is a replacement for getting the enumerator, calling while(enumerator.MoveNext()) and setting a variable to enumerator.Current. (and at the end calling Dispose, if possible). So, the best solution for this is doing something like:
using(var enumerator = enumerable.GetEnumerator())
{
if (enumerator.MoveNext())
{
do
{
var someVariable = enumerator.Current;... the loop code... } while(enumerator.MoveNext());
}
else
{
... the else you want ...
}
}And you can even create a method using delegates Action<T> for the value and non-generic Action for the else. Something like:
ForEachOrElse(IEnumerable<T> enumerable, Action<T> actionForEachValue, action elseAction)
And to use it you call something like:
ForEachOrElse
(
enumerable,
(value) =>
{
... the code for each value...
},
() =>
{
... the code for else ...
}
);modified on Tuesday, March 9, 2010 9:34 AM
-
yes, it does. One could implement it like this:
if (myProductSelection.Count() != 0)
{
//loop through products in selection
foreach (var aProduct in myProductSelection)
{
Console.WriteLine("Found product:" + aProduct.Code);
}
}
else
{
Console.WriteLine("No products found!");
}But why should I? If the foreach loop doesn't get executed, I know I've got the same result as if I used the above if-statement. So imo this gives me redundant code. Or do you disagree?
- Life would be so much easier if I had the source code! - If C# had true garbage collection, most applications would delete themselves upon execution ;)
Ted On The Net wrote:
But why should I?
Because it expresses the intention of the code? I.e. if there are items loop through them otherwise produce message. :)
Regards David R --------------------------------------------------------------- "Every program eventually becomes rococo, and then rubble." - Alan Perlis
-
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#
//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!");
}Try this:
//Print header text
Console.WriteLine("The products that were found:");//Initialize tracker variable
int productsFound = 0;//loop through products in selection
foreach (var aProduct in myProductSelection)
{
Console.WriteLine("Found product: " + aProduct.Code);
productsFound++;
}if (productsFound == 0)
Console.WriteLine("No products were found!");