RichC
RichC

Reputation: 7879

Add an item to an ICollection inside of a Linq query

How can I add one item to a collection inside if a select linq query?

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,
       });

However, I get an error void and null types are incompatible.

I have two entities with (pertinent) properties show below:

User
-----
UserID [PK]
Username
EmailAddress
...

Federation
----------
FederationID [PK]
UserID [FK]
FederatedUsername

However, I get an error Void and null types are incompatible.

Upvotes: 0

Views: 248

Answers (2)

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

new List<Federation>().Add(new Federation { FederatedUsername = u.FederatedUsername })

this piece of code does not return the list, because Add does not return anything.

Use collection initialization syntax instead:

new List<Federation>() { new Federation { FederatedUsername = u.FederatedUsername } }

so it should be:

Federations = u.FederatedUsername != null
                  ? new List<Federation>() {
                        new Federation {
                            FederatedUsername = u.FederatedUsername
                        }
                     }
                  : null,

Upvotes: 2

Enigmativity
Enigmativity

Reputation: 117047

Try something like this:

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(),
        });

Upvotes: 1

Related Questions