c# - 如何在lambda表达式的select方法中编写多个语句

标签 c# .net linq lambda

我正在尝试使用 XDocument 准备 XML 文档,同时向特定词典添加项目,但遇到了以下错误。

无法从用法中推断出方法“System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System.Func)”的类型参数。尝试显式指定类型参数。

代码片段是

Dictionary<string, string> userguid = new Dictionary<string, string>();

    XDocument XMLDoc =
                new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
                new XElement("NewDataSet",
                  new XElement("Users",
                      new XElement("UserID", userid),
                      new XElement("FullName", "anyone"),
                      new XElement("UserName", "anyone"),
                      new XElement("Password", 123),
                      new XElement("Description", "anyone"),
                      new XElement("DomainName", string.Empty),
                      new XElement("Mailbox_Size", 20),
                      new XElement("Enabled", "True"),
                      new XElement("Permissions", 14),
                      new XElement("CreationTime", "2011-07-19T17:45:58.53125+05:30")
                      ),
                userNames.Select((item, value) =>
                   {
                       new XElement("Users",
                          new XElement("UserID", Guid.NewGuid().ToString("N")),
                          new XElement("FullName", item.Trim()),
                          new XElement("UserName", item.Trim()),
                          new XElement("Password", passwords[value].Trim()),
                          new XElement("Description", item.Trim()),
                          new XElement("DomainName", string.Empty),
                          new XElement("Mailbox_Size", 20),
                          new XElement("Enabled", "True"),
                          new XElement("Permissions", 14),
                          new XElement("CreationTime", "2011-07-19T17:45:58.53125+05:30"));
                        userguid.Add(userid, emailAddresses[value].Trim());
                   }
                        )
                      ));

最佳答案

你几乎做对了,但是当使用语句 block ({…})时,你需要显式返回一个合适的值,因为Select 接受一个返回值的委托(delegate)。

(记住,缩写的单表达式 lambda:

x => expr(x)

实际上只是完整版本的缩写:

x => { return expr(x); }

)

关于c# - 如何在lambda表达式的select方法中编写多个语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26254543/

相关文章:

c# - 有没有办法改变 ClickOnce "App has an update"自动消息?

C#:如何将 BITMAP 字节数组转换为 JPEG 格式?

c# - 合并键匹配的键值对列表

c# - 具有 LINQ 扩展方法的多个 WHERE 子句

c# - 是否可以用 Linq/Lambda 方法重写以下代码

c# - .NET 中的简单 rsa 加密/解密?

C# - Linq 使用 List 和 Where 子句优化代码

c# - 实体中的业务逻辑并注入(inject) DbContext

c# - 正则表达式/字符串分割

.net - 有人成功使用免注册COM和.NET组件吗?