-
Is it possible to order a set of data by a custom order? For example I hoped the following would allow me to filter the items within a list and then order it by the position it appears, however the contains works fine but the order by doesn't appear to be supported. var ids = new List<int> { 2, 3, 4 };
var foo = session.Query<Foo>()
.Where(x => ids.Contains(x.Id))
.OrderBy(x => ids.IndexOf(x.Id))
.ToList(); |
Beta Was this translation helpful? Give feedback.
Answered by
nfplee
Jul 19, 2024
Replies: 2 comments
-
I've come up with the following HQL Generator to achieve this: public class IndexOfHqlGenerator : BaseHqlGeneratorForMethod {
public IndexOfHqlGenerator() {
SupportedMethods = [
ReflectHelper.GetMethodDefinition<IList<int>>(x => x.IndexOf(0)),
ReflectHelper.GetMethodDefinition<List<int>>(x => x.IndexOf(0))
];
}
public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) {
var collection = (IList<int>)((ConstantExpression)targetObject).Value!;
var value = visitor.Visit(arguments[0]).AsExpression();
return treeBuilder.Case(
collection.Select((x, i) => treeBuilder.When(treeBuilder.Equality(value, treeBuilder.Constant(x)), treeBuilder.Constant(i))).ToArray(),
treeBuilder.Constant(collection.Count)
);
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
nfplee
-
I would suggest do in memory ordering for this case. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've come up with the following HQL Generator to achieve this: