linq:转换.single()到查询符号[英] LINQ: convert .Single() to query notation

本文是小编为大家收集整理的关于linq:转换.single()到查询符号的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

所以我知道查询符号

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

等效于点符号

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

但是如何将此点表示法转换为查询符号?

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

我在Google上找不到太多资源.

推荐答案

你不能.查询语法中无法使用许多LINQ函数.充其量,您可以将两者结合起来并做类似

之类的事情
var word = (from p in wordsList
            where p.Id == savedId
            select p).Single()

但是,在简单的情况下点符号"对我来说似乎更可读.

Linq在 msdn 上,有一个关键字列表.您可以从该列表中看到哪些函数集成到语言中.

其他推荐答案

Single在查询符号中没有确切的等效.

最好的方法是将查询包裹在括号中,然后呼叫.

其他推荐答案

您唯一可以做的是:

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

但是它不会完全相同.它将被转换为

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

本文地址:https://www.itbaoku.cn/post/1556812.html

问题描述

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.

推荐答案

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.

其他推荐答案

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.

其他推荐答案

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();