将 IQueryable 从 IQueryable<IGrouping<int, object>> 扁平化为 IQueryable<object>

Flatten IQueryable from IQueryable<IGrouping<int, object>> to IQueryable<object>

我在将 IQueryable<IGrouping<int, object>> 转换为 IQueryable<object> 时遇到问题。

该对象是 class,属性 为 int Index
IGrouping's 键是索引。
我想合并 IQueryable<object>,其中只考虑最低索引。

例如 几个分组

结果应该是 IQueryable<object>,其中只有索引为 3 的对象在里面。

P.S 我需要一个 IQueryable 来对其执行 DateTime DbFunctions。所以希望这可以通过一个 SQL 查询来完成。

您可以使用 OrderBy 对您的组进行排序,然后使用 FirstOrDefault

进行第一组排序
var firstGroup = list.GroupBy(x => x.Index)
  .OrderBy(g => g.Key)
  .FirstOrDefault()
  .AsQueryable();

请看一个example

要按照所述拼合组,您需要:

  1. 按索引对每个组中的对象进行排序
  2. 从每个组中获取第一个顶部对象

此代码示例演示了 LINQ 查询:

IQueryable<MyObject> objects = new[]
{
    new MyObject{ GroupId = 3, Index = 31, OtherProperty = "Group 3 / Index 31" },
    new MyObject{ GroupId = 3, Index = 32, OtherProperty = "Group 3 / Index 32" },
    new MyObject{ GroupId = 3, Index = 32, OtherProperty = "Group 3 / Index 32" },
    new MyObject{ GroupId = 4, Index = 43, OtherProperty = "Group 4 / Index 43" },
    new MyObject{ GroupId = 4, Index = 42, OtherProperty = "Group 4 / Index 42" },
    new MyObject{ GroupId = 4, Index = 45, OtherProperty = "Group 4 / Index 45" },
    new MyObject{ GroupId = 4, Index = 46, OtherProperty = "Group 4 / Index 46" },
    new MyObject{ GroupId = 5, Index = 51, OtherProperty = "Group 5 / Index 51" },
    new MyObject{ GroupId = 5, Index = 54, OtherProperty = "Group 5 / Index 54" },
    new MyObject{ GroupId = 6, Index = 67, OtherProperty = "Group 6 / Index 67" },
    // ...                                                                    
    new MyObject{ GroupId = 6, Index = 63, OtherProperty = "Group 6 / Index 63" }
}.AsQueryable();

IQueryable<IGrouping<int, MyObject>> groups = objects.GroupBy(o => o.GroupId);

IQueryable<MyObject> outcome = groups.Select(grouping => grouping.OrderBy(g => g.Index).First());

List<MyObject> outcomeList = outcome.ToList();

// outcomeList contains: 
// new MyObject{ GroupId = 3, Index = 31, OtherProperty = "Group 3 / Index 31" };
// new MyObject{ GroupId = 4, Index = 42, OtherProperty = "Group 4 / Index 42" };
// new MyObject{ GroupId = 5, Index = 51, OtherProperty = "Group 5 / Index 51" };
// new MyObject{ GroupId = 6, Index = 63, OtherProperty = "Group 6 / Index 63" };

SelectMany

会变平,然后您可以再次排序并按结果排序,无论是第一个还是最后一个。但是对于组中的项目 return 单个结果集 SelectMany 在那里

其实我终于找到了合适的解决方案。 以前答案的问题总是 First() 调用。

list.Where(SomeFilterExpression)
    .GroupBy(e => e.Index)
    .OrderBy(g => g.Key)
    .Take(1)
    .SelectMany(g => g.Select(e => e))
    .Where(SomeAdditionalFilterExpression)
    .ToList()

此代码(尤其是 Take() 仅使用 one SQL 查询帮助我解决了我的问题) 无论如何感谢您的专业知识。