我有一段这样的代码:
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中的参数?
发布评论