gpt4 book ai didi

c# - 从集合中查找一组值

转载 作者:行者123 更新时间:2023-11-30 14:14:10 27 4
gpt4 key购买 nike

我有一些代码可以根据过滤值过滤一组已排序的对象。例如,我想找到 Name=="searchquery" 所在的对象.然后我想从该集合中获取前 X 值。

我的问题:

  • 我的收藏是 List<T> .此集合是否保证排序顺序?

  • 如果是这样,是否有内置方法来查找满足条件的前 X 个对象?我正在寻找类似

    的东西
    collection.FindAll(o=>o.Name=="searchquery",100);

    这将给我满足条件的前 100 个对象。原因是性能,一旦找到我的 100 个对象,我不想继续检查整个集合。

  • 如果我写:

    collection.FindAll(o=>o.Name=="searchquery").Take(100);

    运行时是否足够智能以在达到 100 时停止检查?

我当然可以自己实现它,但如果有内置方式(如 LInQ 方法),我更愿意使用它。

最佳答案

collection.Where(o=>o.Name=="searchquery").Take(100)

顺序应与原始列表的顺序相同,一旦它取了 100 个元素,它将停止检查(Where 返回一个仅在您取元素时计算的枚举)。来自 the documentation :

This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using foreach in Visual C# or For Each in Visual Basic.

如果您需要不同的排序顺序,则必须指定它(这当然意味着您别无选择,只能检查所有元素)。

关于c# - 从集合中查找一组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12723156/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com