Using anonymous types - one variable choose two di

2019-08-12 06:25发布

问题:

I want to variable take one of two queries but there are two different tables and I have error "Type of conditional expression cannot be determined because there is no implicit conversion between System.Linq.IQueryable<WGamesTicket> and System.Linq.IQueryable<AllGamesTicket>

           var dsakj = (type == "mix") ?
                (from el in objDC.WGamesTickets
                 where el.ticket.time == DTtemp
                     //&& el.typeOfGame == "mix"
                 select el)
                 :
                 (from el in objDC.AllGamesTickets
                  where el.ticket.time == DTtemp
                  //&& el.typeOfGame == "eng"
                  select el);

回答1:

You'll have to cast to a new custom class. For example, you're pulling from two different tables, but maybe you want to collect the id and name from each. So change your code to:

var dsakj = (type == "mix") ?
            (from el in objDC.WGamesTickets
             where el.ticket.time == DTtemp
                 //&& el.typeOfGame == "mix"
             select new myCustomObject()
             {
                 id = el.id,
                 name = el.name,
             })
             :
             (from el in objDC.AllGamesTickets
              where el.ticket.time == DTtemp
              //&& el.typeOfGame == "eng"
             select new myCustomObject()
             {
                 id = el.id,
                 name = el.name,
             });


回答2:

the result of your queries is of a different type, your first is IQueryable<WGamesTickets>, the second IQueryable<AllGamesTickets>. For this reason the type for the "var" variable dsakj cannot be determined.

You could both project to a common class type:

 var dsakj = (type == "mix") ?
                (from el in objDC.WGamesTickets
                 where el.ticket.time == DTtemp
                     //&& el.typeOfGame == "mix"
                 select new GameTicket() { Type = el.typeOfGame} )
                 :
                 (from el in objDC.AllGamesTickets
                  where el.ticket.time == DTtemp
                  //&& el.typeOfGame == "eng"
                  select new GameTicket() { Type = el.typeOfGame} ));

This would have the disadvantage though that you have to "manually" copy the properties into the new GameTicket class instance.