【发布时间】:2017-09-26 21:37:45
【问题描述】:
我正在尝试在动态 linq 中连接字符串,即在常规 linq 中像 string.Join(",", g.Select(i => i.item1)) 一样
我的动态 linq 看起来像这样
result.AsEnumerable().AsQueryable().GroupBy("new {it.id.ToString() as entity_id, it[\"item2\"] as item2}", "it").Select("new{key.entity_id, key.item2,
String.Join(\", \", it.Select(it[\"item1\"].ToString())) as item1}")
但它显然不起作用,任何想法 我只想要每个组的逗号分隔字符串
编辑添加的数据示例:
只是为了说明数据问题 它的样子:
注意:对于 PK 1,item1 重复两次,因为它来自 N:N 关系,我需要在 pk 上对它进行 Group Concat
已解决
我找到了解决此问题的方法,在我的情况下,我需要根据 pil0t 的How to implement SelectMany in System.Linq.Dynamic ExpressionParser 向 System.Linq.Dynamic 添加更多功能 根据您需要更改的答案
1) 签名接口IEnumerableSignatures 并添加到它:
void Select(string selector);
void SelectMany(string selector);/*not needed for this but good to have*/
2) 根据他/她的回答修改 ParseAggregate 函数以添加
....
if (signature.Name == "Min" || signature.Name == "Max")
{
typeArgs = new Type[] { elementType, args[0].Type };
}
else if (signature.Name == "Select")
{
typeArgs = new Type[] { elementType, Expression.Lambda(args[0],innerIt).Body.Type};
}
else if (signature.Name == "SelectMany")
{
var type = Expression.Lambda(args[0], innerIt).Body.Type;
var interfaces = type.GetInterfaces().Union(new[] { type });
Type resultType = interfaces.Single(a => a.Name == typeof(IEnumerable<>).Name).GetGenericArguments()[0];
typeArgs = new Type[] { elementType, resultType };
}
....
3) 重新编译添加到项目中
4) 使用如下:String.Join(\", \", Select(it[\"item1\"].ToString())
【问题讨论】:
标签: c# dynamic-linq