1

I am trying to use elvis operator to achieve something like this

List<string> list = new List<string> { "str1", "str2", "str3"};

string searchkey = "str4"; // this does not exist in the list so will use elvis operator before picking the first from the resulting sequence.

var result = list.where(s=>(s.Contains(searchkey)))?.First();

I expect result to be null but the code actually throws an exception.

6
  • 8
    1. That's not the Elvis Operator, 2. Where should be capitalized, 3. Where will never return null Commented Sep 8, 2016 at 20:00
  • 2
    What is the actual code and error message? Commented Sep 8, 2016 at 20:00
  • Also, is your actual requirement "return the item if it's in the list, otherwise return the first item in the list"? Commented Sep 8, 2016 at 20:02
  • You can use .FirstorDefault() instead Commented Sep 8, 2016 at 20:04
  • This is called the Null Conditional Operator, not the Elvis operator, as D Stanley mentioned: msdn.microsoft.com/en-us/library/dn986595.aspx Commented Sep 8, 2016 at 20:04

2 Answers 2

2

The problem is that

list.Where(s=>(s.Contains(searchkey)))

does not return null; it returns an empty sequence, which is not the same thing.

If you would like to get a null when the sequence of objects is empty, use FirstOrDefault:

var result = list.FirstOrDefault(s=>(s.Contains(searchkey)));

Note: C#'s version of "Elvis Operator" is ||, not ?.. The operator in your code is called null conditional operator.

Sign up to request clarification or add additional context in comments.

1 Comment

'||' is logical or; '?.' is indeed the elvis operator
0

Because Where operator returns anything to enumerate and First() cannot be evaluated. You may use FirstOrDefault()

2 Comments

"Where operator returns null" no it doesn't...
Ok it doesn't return null, but returns no element to iterate. I will edit. By the way, thank you for heads up.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.