c# - select 子句中的表达式类型不正确。调用 'Select' 时类型推断失败

标签 c# linq

我正在学习 LINQ,并正在尝试这个与 select 子句相关的示例。

var q = from c in xmlDoc.Descendants("site").Where(tech => tech.Attribute("technical").Value == "true")
                   .Select(n => new { SiteName = n.Element("name").Value});

上面的查询给了我一个错误:
select 子句中的表达式类型不正确。调用“Select”时类型推断失败。

上面的语法有什么问题?

除了上述内容之外,我还必须将选定的选项转换为ToDictionary。如何通过 LINQ 在同一个查询中完成?

我想到的第三个问题是关于编写相同查询的不同语法(例如:下面的第二种方法编写示例)。首选什么语法以及为什么?

from c in xmlDoc.Descendants
where c.Attriubute("technical").Value == "true"
select c.Element("site").Value;

最佳答案

1. 您将 lambda 表达式与 linq 语法混合在一起。以 linq 开始,以 lambda 表达式结束。试试这个

 var q = xmlDoc.Descendants("site").Where(tech => tech.Attribute("technical").Value == "true")
                   .Select(n => new { SiteName = n.Element("name").Value});

或者您应该在 linq 中使用整个查询

var q = from c in xmlDoc.Descendants("site") where c.Attribute("technical").Value == "true"
                   select new { SiteName = c.Element("name").Value};

2. 只需在查询末尾使用 ToDictionary

var q = xmlDoc.Descendants("site").Where(tech => tech.Attribute("technical").Value == "true")
                   .Select(n => new { SiteName = n.Element("name").Value,Key= n.Element("id").Value }).ToDictionary(n=>n.Key,l=>l.SiteName);

n=>n.Key 将是字典的键,l=>l.siteName 将是值。

3. 创建此类查询有两种方法,一种是使用 linq,另一种是使用使用 lambda 表达式作为参数的方法。两者都很简单,linq 在某种程度上类似于 SQL 查询,而使用 lambda 的方法更像是通过描述方法操作数据的简写。我个人喜欢使用 lambda 的面向方法的方式,因为它更具顺序可读性。

关于c# - select 子句中的表达式类型不正确。调用 'Select' 时类型推断失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11113027/

相关文章:

c# - 如何更改默认的 Visual Studio C# 新类文件模板?

c# - 在 mysql 连接上“使用”

c# - Autofac,解析操作结束

c# - 给定总分区数和分区数对列表进行分区

c# - 有没有办法使用 Mage/MageUI 为 ClickOnce 应用程序 list 指定应用程序图标?

c# - 使用 LINQ 在组内排序

c# - 选择具有组最小值的组的所有元素

c# - C# 中的 unsigned int mysql

c# - 为什么方法不会从 LINQ Where 方法中执行

c# - 不能将 int 转换为 T,其中 T 是 bool。有没有办法用 C# 做到这一点?