如何在lambda表达式的select方法中写入多个语句
本文关键字:语句 方法 select lambda 表达式 | 更新日期: 2023-09-27 18:25:51
在向特定Dictionary添加项目的同时,我正试图使用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());
}
)
));
您几乎做对了,但在使用语句块({…}
)时,您需要显式地为return
指定一个合适的值,因为Select
接受一个返回值的委托。
(记住,缩写的单个表达式lambda:
x => expr(x)
实际上只是完整版本的缩写:
x => { return expr(x); }
)
当您使用块而不是lambda(在select方法中,我的意思是)时,您应该返回结果。我的意思是userNames.Select((item, value) => { /* return the result here... */ });
:
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) =>{
userguid.Add(userid, emailAddresses[value].Trim());
return 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"));
}
)
));