我正在尝试初始化IEnumerable,但我收到了错误
无法隐式转换类型'System.Collections.Generic.IEnumerable<>' to System.Collections.Generic.IEnumerable.KeyValuePair>'
代码
IEnumerable<KeyValuePair<Guid, String>> users;
if (Roles.IsUserInRole("Administrator"))
{
users = _systemUserCommand.LookupUsersInRole(null, query)
.Select(s => new { s.SystemUserId, Text = string.Format("{0} {1}", s.FirstName, s.LastName) });
}
我该如何解决这个问题?
答案 0 :(得分:6)
不是使用IEnumerable<KeyValuePair<Guid, String>>
,而不是Dictionary<Guid, String>
?
并且您无法在指定类型的列表中插入匿名类型,您需要创建new KeyValuePair
(或者如果您正在使用它,只需执行.ToDictionary()
)
假设您正在使用词典方法:
Dictionary<Guid, string> users;
users = _systemUserCommand.LookupUsersInRole(null, query)
.ToDictionary(
s => s.SystemUserId,
s => string.Format("{0} {1}", s.FirstName, s.LastName)
);
假设您正在使用IEnumerable方法:
IEnumerable<KeyValuePair<Guid, String>> users;
users = _systemUserCommand.LookupUsersInRole(null, query)
.Select(s =>new KeyValuePair<Guid, String>(
s.SystemUserId,
string.Format("{0} {1}", s.FirstName, s.LastName)
));