有没有一种方法可以将运算符指定为LINQ中的参数?

编程入门 行业动态 更新时间:2024-10-12 20:26:31
本文介绍了有没有一种方法可以将运算符指定为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中的参数?

本文发布于:2023-11-17 08:59:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1609541.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:运算符   参数   方法   LINQ

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!