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.

yonas
  • 21
  • 2
  • 8
    1. That's not the [Elvis Operator](https://en.wikipedia.org/wiki/Elvis_operator), 2. `Where` should be capitalized, 3. [`Where` will never return `null`](http://stackoverflow.com/questions/1191919/what-does-linq-return-when-the-results-are-empty) – D Stanley Sep 08 '16 at 20:00
  • 2
    What is the _actual_ code and error message? – D Stanley Sep 08 '16 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"? – D Stanley Sep 08 '16 at 20:02
  • You can use .FirstorDefault() instead – Slai Sep 08 '16 at 20:04
  • This is called the `Null Conditional Operator`, not the Elvis operator, as D Stanley mentioned: https://msdn.microsoft.com/en-us/library/dn986595.aspx – David L Sep 08 '16 at 20:04
  • A year or two back, I saw a talk by a MS C#6 evangelist who called null-conditional the Elvis operator. I'm not mistaken; the talk was about the new features in C#6. I'd never heard the term, and I learned the ternary `?:` when I started learning C in 1995. So it's quite possible that OP heard "Elvis Operator" from somebody you'd think would know what he was talking about. – 15ee8f99-57ff-4f92-890c-b56153 Sep 08 '16 at 20:15

2 Answers2

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

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

Halis S.
  • 446
  • 2
  • 11
  • 3
    "`Where` operator returns `null`" [no it doesn't](http://stackoverflow.com/questions/1191919/what-does-linq-return-when-the-results-are-empty)... – D Stanley Sep 08 '16 at 20:02
  • Ok it doesn't return null, but returns no element to iterate. I will edit. By the way, thank you for heads up. – Halis S. Sep 08 '16 at 20:06