0

我有一段像这样的代码:

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

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

要获得具有值的记录,所有更改都是 == 到 !=

那么是否可以将这段代码放在一个方法中,该方法将根据需要将比较从 == 更改为 != 或者我是否重复查询以这样做:

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

问候。

4

4 回答 4

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

那将是equals函数。

我要做的就是把它们放在字典里:

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

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

于 2013-06-10T11:10:24.943 回答
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;     
}
于 2013-06-10T11:09:02.050 回答
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();
于 2013-06-10T11:09:15.310 回答
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();
于 2013-06-10T11:14:20.677 回答