Theo
Theo

Reputation: 473

Linq GroupBy on multiple columns with potentials null value

I'm trying to make this work :

 var customerSearchResult = customers.GroupBy(                               
            x => new {
                x.CustomerID,
                x.email,
                x.CreatedOn,
                x.FirstName,
                x.LastName,
                x.Profile == null ? -1 : x.Profile.Value
            })
            .Select(csr => new CustomerSearchResult
            {
                CustomerID = csr.Key.CustomerID,
                Email = csr.Key.email,
                CreatedOn = csr.Key.CreatedOn

            });

I am getting an

Error CS0746 Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

Because of this line x.Profile == null ? -1 : x.Profile.Value Profile can be null.

Any idea how to do this?

Upvotes: 8

Views: 6008

Answers (1)

Maksim Simkin
Maksim Simkin

Reputation: 9679

Declare name for this variable in Anonymous class:

var customerSearchResult = customers.GroupBy(                               
            x => new {
                x.CustomerID,
                x.email,
                x.CreatedOn,
                x.FirstName,
                x.LastName,
                Profile = x.Profile == null ? -1 : x.Profile.Value
            })
            .Select(csr => new CustomerSearchResult
            {
                CustomerID = csr.Key.CustomerID,
                Email = csr.Key.email,
                CreatedOn = csr.Key.CreatedOn
            });

As @Abion47 mentioned in comment, you could simplify your assihnment as:

Profile = x.Profile?.Value ?? -1

Upvotes: 9

Related Questions