meaning something like...
foreach(blah b in blahblahs)
{
writeOnMoon(b.name);
}
default
{
writeOnMoon("No Blahs!");
}
default or, otherwise, or something like that, if this does not exist... do you think it should?
meaning something like...
foreach(blah b in blahblahs)
{
writeOnMoon(b.name);
}
default
{
writeOnMoon("No Blahs!");
}
default or, otherwise, or something like that, if this does not exist... do you think it should?
how about:
bool run = false;
foreach (var item in collection)
{
run = true;
// Do stuff
}
if (!run)
{
// Other Stuff
}
Nope, there's no specific syntax in C# that will do what you want.
You're forced to devise your own approach (like what JDunkerley's example shows).
There isn't a keyword to do this.
You can do:
if (blahblahs.Any())
{
foreach(blah b in blahblahs)
{
writeOnMoon(b.name);
}
}
else
{
writeOnMoon("No Blahs!");
}
This doesn't exist.
I don't think this should be in the language because it really doesn't allow you to do anything new, nor does it make any current complex tasks much simpler.
No, but you could write an extension method so you could write:
collection.ForEachOrDefault(b =>
{
WriteOnMoon(b.name);
}, () =>
{
WriteOnMoon("No Blahs!");
});
Admittedly I don't think I'd recommend it... but here's the code:
public static void ForEachOrDefault<T>(this IEnumerable<T> source,
Action<T> forEachAction, Action defaultAction)
{
// Nullity checking omitted for brevity
bool gotAny = false;
foreach (T t in source)
{
gotAny = true;
forEachAction(t);
}
if (!gotAny)
{
defaultAction();
}
}
IEnumerable myCollection = GetCollection();
if(myCollection.Any())
{
foreach(var item in myCollection)
{
//Do something
}
}
else
{
// Do something else
}
No. But you can try to invent a simple extension method - for simple cases it will do...
public static class EnumerableExtension
{
public static void IfEmpty<T>(this IEnumerable<T> list, Action<IEnumerable<T>> action)
{
if (list.Count() == 0)
action(list);
}
}
foreach (var v in blabla)
{
}
blabla.IfEmpty(x => log("List is empty"));
Maybe you'll even be able to create re-usable actions then. Though it doesn't really make much sense.
Python has this (for ... else ...) and I really miss it in C#.
With LINQ you can do something like this:
public static IEnumerable<T> IfEmpty<T>(this IEnumerable<T> source, Action action)
{
var enumerator = source.GetEnumerator();
if (enumerator.MoveNext())
do yield return enumerator.Current; while (enumerator.MoveNext());
else
action();
}
mylistofobjects.Each(...).IfEmpty(() => { /* empty list */ });