Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 807
Theo Avatar asked Dec 30 '16 21:12

Theo


1 Answers

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
like image 71
Maksim Simkin Avatar answered Nov 04 '22 18:11

Maksim Simkin