在LINQ的where子句中使用NaturalSortComparer[英] Use a NaturalSortComparer in a LINQ Where Clause

本文是小编为大家收集整理的关于在LINQ的where子句中使用NaturalSortComparer的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

假设我有一个带有字符串字段 [ProductString] 的表 Table1,其中包含值:字母、字母数字或数字:例如 ABC、B4、U2、C 5、100、U1、U5、U6、U11

我希望能够采用"ProductString >= U5"之类的 where 子句,并将其作为字符串传递给 LINQ 语句,以便它计算

Table1.Where(t=> t.ProductString >= 'U5');

通常这将返回结果 U5 和 U6.

但是,我希望能够使用 NaturalSortComparer不知何故,返回的结果是 U5、U6 和 U11.

我知道如何在 OrderBy 中使用比较器,因为我希望能够在 Where 阶段使用它.

推荐答案

使用自然排序比较器:

var comparer = new NaturalComparer();
Table1.Where(t=> 
    comparer.Compare(t.ProductString, "U5") >= 0);

假设您所有的产品字符串都采用 U%number% 格式,那么为什么不滥用这个事实呢?

Table1.Where(t=> int.Parse(t.ProductString.Replace("U","")) >= 5);

如果您使用的是 LINQ to Entities,我不确定这是否会编译为存储表达式(即 SQL 知道如何处理它 - 我想应该这样做).

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

问题描述

Say I have a table Table1 with a string field [ProductString] with values: Alpha, alphanumeric or numeric: eg ABC, B4, U2, C 5, 100, U1, U5, U6, U11

I want to be able to take a where clause like "ProductString >= U5", and pass this to a LINQ statement as a string so it evaluates

Table1.Where(t=> t.ProductString >= 'U5');

Normally this would return results U5 and U6.

However, this I want to be able to use a NaturalSortComparer somehow so that the results returned are U5, U6 and U11.

I know how to use the comparer in an OrderBy, by I wanted to be able to use it at the Where stage.

推荐答案

Using natural sort comparer:

var comparer = new NaturalComparer();
Table1.Where(t=> 
    comparer.Compare(t.ProductString, "U5") >= 0);

Presuming all your product strings is on the format U%number% then why not abuse that fact?

Table1.Where(t=> int.Parse(t.ProductString.Replace("U","")) >= 5);

If you're using LINQ to Entities I'm not certain this will compile to a store expression (i.e that SQL knows what to do with this - I guess it should).