繁体   English   中英

从IQueryable展平IQueryable <IGrouping<int, object> &gt;到IQueryable <object>

[英]Flatten IQueryable from IQueryable<IGrouping<int, object>> to IQueryable<object>

我将IQueryable<IGrouping<int, object>>IQueryable<object>遇到问题。

该对象是一个具有int Index属性的类。
IGrouping's键是该索引。
我想获得一个合并的IQueryable<object> ,其中仅考虑最低索引。

例如,几个分组

  • IGrouping<3, object>
  • IGrouping<4, object>
  • IGrouping<4, object>
  • IGrouping<5, object>
  • IGrouping<6, object>
  • IGrouping<3, object>
  • IGrouping<3, object>

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

PS我需要一个IQueryable来执行DateTime DbFunctions。 因此,希望可以通过一个SQL查询来完成。

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

var firstGroup = list.GroupBy(x => x.Index)
  .OrderBy(g => g.Key)
  .FirstOrDefault()
  .AsQueryable();

请看一个例子

要按照说明压平组,您需要:

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

实际上,我终于找到了合适的解决方案。 先前答案的问题始终是First()调用。

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

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

全选

将会变平,然后您可以再次按结果排序或按结果排序(第一个或最后一个)。 但是对于“组中的项目”要返回单个结果集,SelectMany在那里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM