c# – 通过获取原始实体Linq到Collections Group
发布时间:2020-12-16 01:50:57 所属栏目:百科 来源:网络整理
导读:我正在使用以下代码对工具集合进行分组: var filteredTools = from t in tools group t by new { t.ModuleName,t.Number} into g select new { ModuleName = g.Key,Values = g }; tools是一个简单的集合,定义如下: ListTool tools 执行分组后,我得到3行(从
我正在使用以下代码对工具集合进行分组:
var filteredTools = from t in tools group t by new { t.ModuleName,t.Number} into g select new { ModuleName = g.Key,Values = g }; tools是一个简单的集合,定义如下: List<Tool> tools 执行分组后,我得到3行(从40行),因此分组工作正常.行具有g.Key的键,值是分组条件.无论如何都要将它与原始工具联系起来.也许每个工具的密钥都应该是唯一的,因此在执行分组后,我可以从工具集中获取原始工具. 解决方法
是的,这些工具仍然存在于每个组中:
foreach (var group in filteredTools) { // This is actually an anonymous type... Console.WriteLine("Module name: {0}",group.ModuleName); foreach (Tool tool in group.Values) { Console.WriteLine(" Tool: {0}",tool); } } 说实话,你不需要在这里选择你的匿名类型.你可以使用: var filteredTools = tools.GroupBy(t => new { t.ModuleName,t.Number}); foreach (var group in filteredTools) { // This is actually an anonymous type... Console.WriteLine("Module name: {0}",group.Key); foreach (Tool tool in group) { Console.WriteLine(" Tool: {0}",tool); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |