有没有办法在LINQ中将运算符指定为参数?

时间:2013-06-10 11:05:06

标签: c# linq

我有一段代码如下:

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

这只给了我那些空字符串作为键值的rec。

要获得带有值的recs,所有更改都是== to!=

因此可以将这段代码放在一个方法中,根据需要将比较从==更改为!=或者重复查询以执行此操作:

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

问候。

4 个答案:

答案 0 :(得分:3)

不完全,但是如果你稍微修改一下LINQ查询,你可以做一些类似的事情:

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

这将是等于函数。

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

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

这比其他答案更好,因为它也可以扩展到其他运营商。

答案 1 :(得分:1)

我猜你正在寻找类似的东西:

function GetRecs(bool EmptyKey)    
{    
   var Keys = (from recs in allRecords
                         where EmptyKey == (recs.Key == string.Empty)
                         orderby recs.Key
                         select recs).ToList();
   return Keys;     
}

答案 2 :(得分:0)

您可以传递isEmpty过滤器,并将其与recs.Key == String.Empty

的结果进行比较
bool isEmpty = true;
var keys = (from recs in allRecords
            where (recs.Key == String.Empty) == isEmpty
            orderby recs.Key
            select recs).ToList();

答案 3 :(得分:0)

这样的事情原则上应该起作用..

Func<bool> notEmpty = (Key) => {return !Key.IsNullOrEmpty();}
Func<bool> empty = (Key) => {return Key.IsNullOrEmpty();}

Func<bool> comparer = notEmpty

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