用Linq的动态键对数据进行分组[英] Grouping data with dynamic keys with Linq

本文是小编为大家收集整理的关于用Linq的动态键对数据进行分组的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我正在使用 System.Linq.Dynamic 将对象列表分组到具有两个代码的对象列表的新分组列表中:

Dim lstGroupedFilterNew = lstDataSource _
                .GroupBy("New (Unit_ID, Itinerary_ID Driver_ID)", "grp") _
                .[Select](Function(grp) grp.ToList()).ToList()

但我收到错误 lambda 表达式无法转换为"字符串",因为"字符串"不是我的选择子句中的委托类型.

推荐答案

我选择不使用 Linq.Dynamic,我发现了一种验证条件的方法,可以将键动态添加到我的 GroupBy 子句中,结果是这样的:

Dim lstGroupedFilter = (From t In lstDataSource Group t By __groupByKey1__ = _
                          New With {Key .Unit_ID = (If(blnUnit, t.Unit_ID, 0)), Key .Itinerary_ID = If(blnItinerary, t.Itinerary_ID, 0), Key .Driver_ID = If(blnDriver, t.Driver_ID, 0)} _
                          Into g = Group Select g.ToList()).ToList()

这是一个动态添加键并生成类似于此的结果的选项 解决方案.

本文地址:https://www.itbaoku.cn/post/1557166.html

问题描述

I'm using System.Linq.Dynamic to group a list of objects into a new grouped list of list of objects with the both code:

Dim lstGroupedFilterNew = lstDataSource _
                .GroupBy("New (Unit_ID, Itinerary_ID Driver_ID)", "grp") _
                .[Select](Function(grp) grp.ToList()).ToList()

But i'm get error lambda expression cannot be converted to 'string' because 'string' is not a delegate type on my select clause.

推荐答案

I chose not to use Linq.Dynamic, I discovered a way to verify conditions to dynamically add the keys to my GroupBy clause, the result is this:

Dim lstGroupedFilter = (From t In lstDataSource Group t By __groupByKey1__ = _
                          New With {Key .Unit_ID = (If(blnUnit, t.Unit_ID, 0)), Key .Itinerary_ID = If(blnItinerary, t.Itinerary_ID, 0), Key .Driver_ID = If(blnDriver, t.Driver_ID, 0)} _
                          Into g = Group Select g.ToList()).ToList()

This is an option to dynamically add keys and generate a result similar to this solution.