Click here to Skip to main content
15,912,400 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello people,

I want use the ternary operator like this, but it doesn't work.

C#
var itemToRemove = myCollection.Any(p => p != null).FirstOrDefault();
itemToRemove != null ?? myCollection.Remove(itemToRemove); //this don't compile!


It's Possible?
Posted
Updated 8-Jan-19 3:24am
Comments
MCY 13-Feb-14 10:10am    
why not use if?
BillWoodruff 13-Feb-14 12:20pm    
@MCY actually, you can achieve what the OP is obviously trying to do here without an 'if: see my solution below (note: at the time I wrote my response, OriginalGriff's solution was not visible here).
johannesnestler 13-Feb-14 10:47am    
where is a ternary operator (there is only one in .NET and I don't see it in your sample)? You mean the null-coalescing operator? So you can't use the operator "like this" because you used wrong syntax, and from given example it seems you also have more of a "how should I do it" problem. So what you want to achieve in the end?
Just to sum up what's wrong:
Any doesn't return collection (maybe don't use syntactic sugar like var if you don't know how to use it - if you would have written "bool" there, the error may had been obviouse to you)
So a bool can't be null
You are not assigning something so "? :" and "??" operators won't work (MSDN? just hit F1 in VS on the Operator...)
You have compile errors - read them?
EduChapow 13-Feb-14 14:36pm    
thank u everbody

There are a couple of problems here:
1) Any returns a bool, not a collection, so you can't use FirstOrDefault on it.
2) The null-coalescing operator does not work like that. Read the MSDN description: ?? OPerator[^]

I'm not quite sure what the heck you think that code should achieve, so I can't really suggest anything to fix it - perhaps if you told us what you were trying to do it might help?
 
Share this answer
 
Comments
EduChapow 13-Feb-14 11:57am    
OriginalGriff, thanks 4u help!
That's a just example, i write very fast. my really question is!

i can do something like this:
itemToRemove != null ?? myCollection.Remove(itemToRemove);

consider itemToRemove is ok
OriginalGriff 13-Feb-14 12:12pm    
No. Stop and think: what does the ?? operator *do*?
Firstly, it isn't a statement - ?? always returns a value from one side or other and there is nowhere for that result to go.
Secondly, the left and right sides must be the same type - this is fine in your example.
Thirdly, even if you do assign the value so the compilation error goes away:
bool b = itemToRemove != null ?? myCollection.Remove(itemToRemove);
The Remove will never be called, because the != operator always returns a bool, which is a Value type and hence can't hold a null value, so the right will never be actioned.

What are you trying to do?
EduChapow 13-Feb-14 14:35pm    
thanks man, you answer my quention.

"Firstly, it isn't a statement - ?? always returns a value from one side or other and there is nowhere for that result to go."

So, now i'm using a if/else normally.

i just want resolve this in one line... ^^


OriginalGriff 13-Feb-14 14:48pm    
You're welcome!
But in that case, I suspect you misread something! :laugh:
There are two operators that use '?': The null-coelescing operator:
a = b ?? c;
where 'a' gets the value of 'b' unless 'b' is null, in which case a becomes 'c'.

And the Ternary operator which is a short-form for an if...else... statement:
if (a)
b = c;
else
b = d;
Can become:
b = a ? c : d;
So if 'a' is true then 'b' becomes 'c', otherwise 'b' becomes 'd'
But...and there is always a but... 'c' and 'd' must be the same type. You can't return null on either side, and you can't return two class instances that are both of a derived type, even if they derive directly from the same base type.

[edit]Typo - single '?' instead of double '??' :doh: - OriginalGriff[/edit]
Further to OriginalGriff's solution,

The Ternary Operator doesn't work like that either
http://www.dotnetperls.com/ternary[^] - the clue is in the name "operator"

Follow the advice from MCY and use if
C#
if( itemToRemove != null)
    myCollection.Remove(itemToRemove);
 
Share this answer
 
Your code does not make use of the ternary operator: you are using the "??" operator which evaluates an argument (a variable), and if the value is non-null, returns the evaluated value; if the value is null, then the value after the "??" is returned. Example:
C#
string s1 = null;

string t1 = s1 ?? "whoop de doo"; // t1 now contains "whoop de doo"

string s2 = "hoop la";

string t2 = s2 ?? "yabba dabba doo" // t2 now contains "hoop la"
You can use the ternary operator, referred to by Microsoft as the "conditional operator," which must always return a value:
C#
string t3 = (s1 != null) ? t2 : "shake, rattle, and roll";
// t3 contains "shake, rattle, and roll"
With both ?? and ternary operators you are limited to one statement in each "segment," and you must return something.

Clearly, your goal here is to remove an item from a collection. Keep in mind that .NET Collections Remove<T> operator returns a boolean value indicating the success or failure of a removal; you can use that return value, or ignore it. If you need to keep track of whether the removal was successful, try this:
C#
bool itemIsRemoved = myCollection.Remove(myCollection.FirstOrDefault(p => p != null));
Here's a challenge:
C#
List<string> lStr = new List<string> {null, string.Empty, "0", "1", "41", "2", "3", "4", "5" };

var itmIsRemoved1 = lStr.Remove(lStr.FirstOrDefault(str => str != null));

var itmIsRemoved2 = lStr.Remove(lStr.FirstOrDefault(str => str == "4"));

var itmIsRemoved3 = lStr.Remove(lStr.FirstOrDefault(str => str == string.Empty));

var itmIsRemoved4 = lStr.Remove(lStr.FirstOrDefault(str => str == null));
What do you think the value of 'itmIsRemoved, and the values in the List of strings, are after each line of the code above is executed ?
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900