有没有一种方法可以将运算符指定为LINQ中的参数? [英] Is there a way to specify an operator as an argument in LINQ?

查看:66
本文介绍了有没有一种方法可以将运算符指定为LINQ中的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段这样的代码:

var emptyKeys = (from recs in allRecords
                         where recs.Key == string.Empty
                         orderby recs.Key
                         select recs).ToList();

这仅给我那些以空字符串作为键值的记录.

this gives me only those recs which have an empty string as key values.

要获得具有所有更改值的记录,就是将==更改为!=

To get the recs with values all that changes is the == to !=

因此可以将这段代码放入一种方法中,该方法将根据需要将比较从==更改为!=,或者我像这样重复查询以做到这一点:

So is it possible to put this piece of code in a method which will change the comparison from == to != based on what's required or do I repeat the query to do it like so:

var emptyKeys = (from recs in allRecords
                         where recs.Key != string.Empty
                         orderby recs.Key
                         select recs).ToList();

致谢.

推荐答案

不完全是,但是,如果您对LINQ查询稍加修改,则可以执行以下操作:

Not quite, but if you slightly modify your LINQ query, you can do something of the sort:

Func<string, string, bool> selectorFunc = (a, b) => a == b;
var emptyKeys = (from recs in allRecords
                         where selectorFunc(recs.Key, string.Empty)
                         orderby recs.Key
                         select recs).ToList();

这将是equals函数.

That will be the equals function.

我要做的是将它们放在字典中:

What I would do is put them in a dictionary:

Dictionary<string, Func<string, string, bool>> selectorDictionary = 
    new Dictionary<string, Func<string, string, bool>>() 
        { {"==", (a, b) => a == b}, {"!=", (a, b) => a != b} };

然后像这样使用它:

Dictionary<string, Func<string, string, bool>> selectorDictionary = 
    new Dictionary<string, Func<string, string, bool>>() 
        { {"==", (a, b) => a == b}, {"!=", (a, b) => a != b} };
Func<string, string, bool> selectorFunc = selectorDictionary[operator];
var emptyKeys = (from recs in allRecords
                         where selectorFunc(recs.Key, string.Empty)
                         orderby recs.Key
                         select recs).ToList();

这比其他答案要好,因为它也可以扩展到其他运算符.

This is better than the other answers as it's expandable to other operators, too.

这篇关于有没有一种方法可以将运算符指定为LINQ中的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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