开发者

Using null coalescing in foreach statement

Trying to figure out how to get the null coalescing operator to work in a foreach loop.

I'm checking to see what a string ends with and based on that, route it to a certain method. Basically what I want to say is....

foreach (String s in strList)
{
    if s.EndsWith("d") ?? Method1(s) ?? Method2(s) ?? "Unknown file type";
}

In attempting to do this, of course you get the "Operator ?? cannot be used on type bool and type string." I know there is other ways to do it, just want to see how it can be done with null coalescing.

Have a good weekend.

@Richard Ev: Oh yes of course. Switch, if else, etc. Was just curious how it could be handled

@Jon Skeet: After reading your comments it hit me, this is just bad! I am interested in two file extensions basically. If a file ends with "abc" for instance, send to m开发者_Go百科ethod 1, if the file ends with "xyz" send to method 2. But what if a file ends with an extension of "hij"...boom, you're done.

Thanks to Brian and GenericTypeTea as well for the thoughful input

I'm content calling it closed.


It looks like you want to use the normal ternary operator, not null coalescing. Something like:

(s.EndsWith("d") ? Method1(s) : Method2(s)) ?? "Unknown file type";

This is equivalent to:

string result;
if (s.EndsWith("d"))
  result = Method1(s);
else
  result = Method2(s);
if (result == null)
  result = "Unknown file type";
return result;


I think you want a combination of the conditional (ternary) operator and the null coalescing operator:

foreach (String s in strList)
{
    string result = (s.EndsWith("d") ? Method1(s) : Method2(s)) 
        ?? "Unknown file type";
}

In simple english, this will do the following:

If s ends with d, then it will try Method1.
If s does not end with d then it will try Method2.
Then if the outcome is null, it will use "Unknown file type"
If the outcome is not null, it will use the result of either A or B


I think the compiler gave you the appropriate answer, you can't.

Null coalescing is essentially this if statement:

if(x == null)
  DoY();
else
  DoZ();

A boolean value cannot be null, so you can't coalesce it like that. I'm not sure what your other methods return, but it seems like you want a simple || operator here.


You should first use the ?? null coalescing operator to guard against a null s reference. Then use the ? ternary operator to choose between Method1 and Method2. Finally use the ?? null coalescing operator again to provide the default value.

foreach (string s in strList)
{
    string computed = s;
    computed = computed ?? String.Empty;
    computed = computed.EndsWith("d") ? Method1(s) : Method2(s);
    computed = computed ?? "Unknown file type";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜