修改Linq以返回第一个匹配值

时间:2015-09-08 11:06:58

标签: c# linq

我正在尝试修改下面的Linq查询以返回最大版本的第一个匹配行。

+----+------+---------+-----+
| PK | Name | Version | abc |
+----+------+---------+-----+
|  1 | Bill |       1 |   7 |
|  2 | Bob  |       1 |   2 |
|  3 | Ben  |       1 |   3 |
|  4 | Bob  |       2 |   2 |
|  5 | Ben  |       2 |   3 |
|  6 | Ben  |       2 |   3 |
+----+------+---------+-----+

目前它将返回:

 +----+------+---------+-----+
    | PK | Name | Version | abc |
    +----+------+---------+-----+
    |  1 | Bill |       1 |   7 |
    |  4 | Bob  |       2 |   2 |
    |  5 | Ben  |       2 |   3 |
    |  6 | Ben  |       2 |   3 |
    +----+------+---------+-----+

当我希望它返回时:

+----+------+---------+-----+
| PK | Name | Version | abc |
+----+------+---------+-----+
|  1 | Bill |       1 |   7 |
|  4 | Bob  |       2 |   2 |
|  5 | Ben  |       2 |   3 |
+----+------+---------+-----+

 var source = (from item in baseSource
                          where item.Version > 0 
                          where item.Published                           
                          where db.abcTest.Where(it => it.Published && it.Name == item.Name).Max(it => it.Version) == item.Version                              
                          orderby item.Name, item.Version descending                             
                          select new
                          {                         
                              item.PK,
                              item.Name,                                 
                              item.Version,
                              item.abc
                          }
                          ).ToList();
            return source;

2 个答案:

答案 0 :(得分:1)

您需要GroupBy: -

var result = baseSource.GroupBy(x => x.Name)
                .Select(x =>
                {
                    var orderedObj = x.OrderByDescending(z => z.Version)
                                      .ThenByDescending(z => z.abc).FirstOrDefault();
                    return new 
                            {
                                 PK = orderedObj.PK,
                                 Name = x.Key,
                                 Version = orderedObj.Version ,
                                 abc = orderedObj.abc
                             };
                };

考虑检查orderedObj是否为空,否则可能会抛出Null引用异常。

答案 1 :(得分:1)

以下使用组功能的代码使其正常工作

zip' [] _ = []
zip' _ [] = []
zip' (x:xs) (y:ys) = (x,y) : zip' xs ys