TakeWhile
扩展方法在其工具提示中有以下注释:“元素的索引用于谓词函数的逻辑”。请注意,此工具提示在普通工具提示中不可见,而仅在变量 sortedDictionary
列表成员的智能感知列表的工具提示中可见。
这正是与 SortedDictionary
结合寻找的内容。
var first = sortedDictionary.First(kv => kv.Key.ToString().StartsWith(searchkey));
var last= sortedDictionary.Last(kv => kv.Key.ToString().StartsWith(searchkey));
var range = sortedDictionary.TakeWhile(kv => kv.Key.ToString().StartsWith(searchkey));
第一个和最后一个项目已找到并正确,但我的收藏范围是空的。
这里有什么问题?我期望一个范围包含 first 和 last 之间的所有项目,包括它们。
我仍然可以使用 first 和 last 找到范围,但是 TakeWhile
使用索引,而 First
和 Last
显然不使用。
编辑:“使用索引”原来与排序无关,但您可以在查询中使用索引。例如。当我将 SortedDictionary
替换为 SortedList
时,我可以:
int ix1 = sortedList.IndexOfKey(first.Key);
int ix2 = sortedList.IndexOfKey(last.Key);
var range = sortedList.SkipWhile((x, i) => i < ix1).TakeWhile((x, i) => i <= ix2);
还有 SortedDictionary
我可以这样做:
var range = sortedList.SkipWhile(x => !x.Key.ToString().StartsWith(searchkey))
.TakeWhile(x => x.Key.ToString().StartsWith(searchkey));
我将不得不测试哪种方法更快,还必须测试 Where 查询。
最佳答案
如果序列中的第一个元素与谓词不匹配,则 TakeWhile方法将退出:
Returns elements from a sequence as long as a specified condition is true
First方法将采用与您的谓词匹配的第一个元素:
Returns the first element in a sequence that satisfies a specified condition
与第一种方法相反,Last方法将采用与您的谓词匹配的最后一个元素:
Returns the last element of a sequence that satisfies a specified condition
我猜测 TakeWhile 提前退出是因为它们在迭代开始时没有与条件匹配的元素。
如果您想要示例中第一个和最后一个元素之间的元素范围(包括第一个和最后一个项目),请尝试以下操作:
var range = sortedDictionary.SkipWhile( x => !x.Equals( first ) )
.TakeWhile( x => !x.Equals( last ) )
.Concat( new SortedDictionary<string, string> { { last.Key, last.Value } } );
或者你可以像我一样不要过度思考这个问题,而是使用 Where
方法,如 Jeff's example 中那样使用更简单的方法。 .
关于c# - 使用 SortedDictionary TakeWhile 返回空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4987833/