如果选择linq查询,如何在集合中添加一个项目?
IEnumerable<User> users
= model.Select(u => new User
{
Username = u.Username,
EmailAddress = u.EmailAddress,
Federations = u.FederatedUsername != null ? new List<Federation>().Add(new Federation { FederatedUsername = u.FederatedUsername }) : null,
});
但是,我收到错误void并且null类型不兼容。
我有两个具有(相关)属性的实体,如下所示:
User
-----
UserID [PK]
Username
EmailAddress
...
Federation
----------
FederationID [PK]
UserID [FK]
FederatedUsername
但是,我收到错误Void和null类型不兼容。
答案 0 :(得分:2)
new List<Federation>().Add(new Federation { FederatedUsername = u.FederatedUsername })
这段代码不会返回列表,因为Add
不会返回任何内容。
改为使用集合初始化语法:
new List<Federation>() { new Federation { FederatedUsername = u.FederatedUsername } }
所以它应该是:
Federations = u.FederatedUsername != null
? new List<Federation>() {
new Federation {
FederatedUsername = u.FederatedUsername
}
}
: null,
答案 1 :(得分:1)
尝试这样的事情:
IEnumerable<User> users =
model
.Select(u => new User
{
Username = u.Username,
EmailAddress = u.EmailAddress,
Federations =
u.FederatedUsername == null
? new List<Federation>() :
(new []
{
new Federation()
{
FederatedUsername = u.FederatedUsername
},
}).ToList(),
});