2013-02-02 33 views
1

我一直在努力寻找解决这个任务问题的答案,尽管在这里不花时间搜索,但我正在解决这个问题。 我已经查看了MIN/MAX子句,但似乎无法正确适用于我的场景。SQL到Linq - 选择第一个匹配的行

我进行这个简单的LINQ查询在那里我搜索的所有行列匹配

using (DataClasses2DataContext db = new DataClasses2DataContext()) 
     { 
      var routes = (

          from txcalllines in db.TxcAllLines 
          where 
           txcalllines.LineName == searchString 
          select txcalllines); 

      return routes.ToList(); 
     } 

而这个返回的结果:

FILE       LINE START    FINISH 
output_txc_45486m.xml   486 North Station  Friswell Place 
SVRAYAO486-20121008-22264.xml 486 Dunoon    Inveraray 
SVRAYAO486-20121008-22265.xml 486 Dunoon    Inveraray 
SVRAYAO486-20121008-22266.xml 486 Dunoon    Inveraray 
SVRGMB04860-20120103-5774.xml 486 BURY    RADCLIFFE 
SVRGMB04860-20120103-5775.xml 486 BURY    RADCLIFFE 
SVRYNAO486-20120217-44588.xml 486 Selby Bus Stn  Pollington Circular 

问题是,运行此查询返回多行(可以看到LINE,START和FINISH是相同的),我只想返回每条路线的第一个匹配行。

所以期望的结果将是:

FILE       LINE START    FINISH 
output_txc_45486m.xml   486 North Station  Friswell Place 
SVRAYAO486-20121008-22264.xml 486 Dunoon    Inveraray 
SVRGMB04860-20120103-5774.xml 486 BURY    RADCLIFFE 
SVRYNAO486-20120217-44588.xml 486 Selby Bus Stn  Pollington Circular 
+0

好的一点,我没有打算调用.ToList()两次。 –

+0

它只是把它放在一个列表中,我的客户端应用程序可以很好地读取它。 (上面的代码是来自WCF服务) –

回答

1

您可以使用GroupBy然后让每组的第一个元素。

var routes = (from txcalllines in db.TxcAllLines 
       where txcalllines.LineName == searchString 
       group txcalllines by new { txcalllines.Start, txcalllines.Finish } into g // Groups the txcalllines by the pair (Start, Finish) 
       select g.First()); // Gets the first intem of the group 
+0

嗨塞德里克,感谢您的答案,但它不编译。它抱怨了几个问题,包括''中的'无效表达术语',并期待少数问题) –

+1

@DanSewell我已更新我的文章(只是将_in_更改为_into)。 –

相关问题