2

So I know the query notation

var word = from s in stringList
           where s.Length == 3
           select s;

is equivalent to the dot notation

var word = stringList
           .Where(s => s.Length == 3)
           .Select(s => s);

But how do you convert this dot notation to a query notation?

var word = wordsList
           .Single(p => p.Id == savedId);

I couldn't find much resources on Google.

RedAces
  • 319
  • 1
  • 3
  • 16
  • 1
    Just stick with the dot notation in this case. It is the cleanest, most concise way to convey (to the programmer) what you're trying to do. – Jonathon Reinhart Jan 17 '14 at 19:38

4 Answers4

6

You can't. A lot of LINQ functions can't be used in the query syntax. At best, you can combine both and do something like

var word = (from p in wordsList
            where p.Id == savedId
            select p).Single()

but in the simple case of collection.Single(condition), the "dot notation" seems more readable to me.

There is a list of keywords used by LINQ on MSDN, you can see which functions are integrated into the language from that list.

shoftee
  • 31
  • 3
  • 7
dee-see
  • 23,668
  • 5
  • 58
  • 91
3

Single doesn't have an exact equivalent in query notation.

The best you can do is to wrap your query in parentheses and call .Single yourself.

Ben
  • 6,023
  • 1
  • 25
  • 40
2

The only thing you can do is:

var word = (from w in wordsList
            where w.Id == savedId
            select w).Single();

but It will not be exactly the same. It will be transformed into

var word = wordsList
           .Where(p => p.Id == savedId)
           .Single();
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
  • As I see it, `.Where(predicate).Single()` and `.Single(predicate)` are functionally identical, and will exhibit the same runtime performance. – Jonathon Reinhart Jan 17 '14 at 19:37
  • 1
    They are functionally identical, but they are not exactly the same. But I'm not sure about the performance. They should be **really, really small difference you should not ever carry about**. – MarcinJuraszek Jan 17 '14 at 19:38
  • Well [this is very interesting](http://stackoverflow.com/questions/21194750/which-is-faster-singlepredicate-or-wherepredicate-single).... – Jonathon Reinhart Jan 17 '14 at 20:05
  • Oh, I know why that is. `Single()` throws exception when it sees second item, `Single(predicate)` iterated entire collection even when it sees second matching element earlier! – MarcinJuraszek Jan 17 '14 at 20:09
0

Single is not part of the query notation. You could change your first example to the following to achieve what you want:

var word = (from s in stringList where s.Length == 3 select s).Single();
Adam Modlin
  • 2,994
  • 2
  • 22
  • 39