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

查看:76
本文介绍了在LINQ Where子句中使用NaturalSortComparer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个表Table1,该表的字符串字段[ProductString]的值是: 字母,字母数字或数字:例如ABC,B4,U2,C 5、100,U1,U5,U6,U11

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

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

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');

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

Normally this would return results U5 and U6.

但是,我希望能够使用 NaturalSortComparer 以某种方式使返回的结果是U5,U6和U11.

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

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

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

推荐答案

使用自然排序比较器:

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

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

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);

如果您使用的是LINQ to Entities,我不确定它是否可以编译为商店表达式(即SQL知道该怎么做-我想应该这样做).

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).

这篇关于在LINQ Where子句中使用NaturalSortComparer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆