Skip to content

Commit 99f623d

Browse files
committed
feat(IQueryable): add extension for selecting columns by list of names
1 parent 2b80385 commit 99f623d

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

src/JsonApiDotNetCore/Extensions/IQueryableExtensions.cs

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
using System;
32
using System.Linq;
43
using System.Linq.Expressions;
@@ -126,5 +125,25 @@ public static IQueryable<TSource> Filter<TSource>(this IQueryable<TSource> sourc
126125
throw new JsonApiException("400", $"Could not cast {filterQuery.PropertyValue} to {property.PropertyType.Name}");
127126
}
128127
}
128+
public static IQueryable<TSource> Select<TSource>(this IQueryable source, string[] columns)
129+
{
130+
var sourceType = source.ElementType;
131+
132+
var resultType = typeof(TSource);
133+
134+
// {model}
135+
var parameter = Expression.Parameter(sourceType, "model");
136+
137+
var bindings = columns.Select(column => Expression.Bind(
138+
resultType.GetProperty(column), Expression.PropertyOrField(parameter, column)));
139+
140+
var body = Expression.MemberInit(Expression.New(resultType), bindings);
141+
142+
var selector = Expression.Lambda(body, parameter);
143+
144+
return source.Provider.CreateQuery<TSource>(
145+
Expression.Call(typeof(Queryable), "Select", new Type[] { sourceType, resultType },
146+
source.Expression, Expression.Quote(selector)));
147+
}
129148
}
130149
}

0 commit comments

Comments
 (0)