我在将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的对象在其中。
我需要一个IQueryable在上面执行DateTime DbFunctions。因此,希望这可以通过一个SQL查询来完成。
发布于 2018-05-28 04:57:01
实际上,我终于找到了一个合适的解决方案。以前回答的问题始终是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查询解决问题)感谢您的专业知识。
发布于 2018-05-25 11:59:26
若要按所描述的方式将组扁平化,您需要:
此代码示例演示了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" };发布于 2018-05-25 11:31:36
您可以使用OrderBy对组进行排序,然后使用FirstOrDefault进行第一组排序。
var firstGroup = list.GroupBy(x => x.Index)
.OrderBy(g => g.Key)
.FirstOrDefault()
.AsQueryable();请看示例
https://stackoverflow.com/questions/50527825
复制相似问题