使用匿名类型 - 一个变量选择两个不同的查询

时间:2011-07-11 17:36:49

标签: c# linq-to-sql

我想变量取两个查询之一,但有两个不同的表,我有错误“无法确定条件表达式的类型,因为System.Linq.IQueryable<WGamesTicket>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);

2 个答案:

答案 0 :(得分:3)

您的查询结果属于不同类型,第一个是IQueryable<WGamesTickets>,第二个IQueryable<AllGamesTickets>。因此,无法确定“var”变量dsakj的类型。

您可以投射到公共类类型:

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

虽然您必须“手动”将属性复制到新的GameTicket类实例中,但这样做会有缺点。

答案 1 :(得分:3)

您必须转换为新的自定义类。例如,您从两个不同的表中提取,但是您可能希望从每个表中收集ID和名称。所以将代码更改为:

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