查找值是否存在于 C# 列表中的最有效方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16059391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Most efficient way to find if a value exists within a C# List
提问by Aaron Benzel
In C# if I have a List of type bool. What is the fastest way to determine if the list contains a true value? I don't need to know how many or where the true value is. I just need to know if one exists. I will be searching many extremely large lists.
在 C# 中,如果我有一个类型为 bool 的列表。确定列表是否包含真值的最快方法是什么?我不需要知道真正的价值是多少或在哪里。我只需要知道是否存在。我将搜索许多非常大的列表。
采纳答案by treze
Use either list.Contains(true) or list.Any(true). For a normal list both have complexity O(n). Since Any() is an extension method though, which needs to invoke delegates, the Contains() might still be a bit faster. But to be sure I would simply test both with a large collection.
使用 list.Contains(true) 或 list.Any(true)。对于普通列表,两者的复杂度均为 O(n)。由于 Any() 是一个需要调用委托的扩展方法,所以 Contains() 可能仍然要快一点。但可以肯定的是,我会简单地用一个大集合来测试两者。
回答by Tim Schmelter
Just use bool trueInList = list.Contains(true);. This loops the list until there's a true.
只需使用bool trueInList = list.Contains(true);. 这会循环列表直到有一个true.
Why do you need something faster with such a simple use-case?
为什么你需要这样一个简单的用例更快的东西?
回答by Hossein Narimani Rad
Try this:
尝试这个:
var result = myBoolList.Any(i => i==true);
回答by user707727
You could use Any().
您可以使用 Any()。
list.Any(b => b);
回答by Jens Kloster
You use the Any(...)
您使用 Any(...)
list.Any(c => c == true);
or just
要不就
list.Any(c => c);
回答by vikky
bool val = false;
Foreach(bool val in listofvalue)
{
val |= val;
}
if(val)
print "List contain true value"
else
print "List contain false value"
回答by Saeed
You can use BinarySearch method of the list.
您可以使用列表的 BinarySearch 方法。
if(list.BinarySearch(true) > 0){...}
回答by usr
This answer provides a different angle on this: Why store the bools in a list? Store them as two ints: int falseCount; int trueCount;.
这个答案提供了一个不同的角度:为什么将布尔值存储在列表中?将它们存储为两个整数:int falseCount; int trueCount;.
Contains-testing is as simple as: trueCount > 0
包含测试非常简单: trueCount > 0
Assuming that you need the list, use List.Containsas it directly searches the underlying array.
假设您需要该列表,请使用List.Containsas 它直接搜索底层数组。
It would be even faster to extract the underlying array using reflection and search it in a hard-coded comparison loop. You can use the literal truethere to compare each element. You can even unroll the loop or do unsafe code tricks.
使用反射提取底层数组并在硬编码比较循环中搜索它会更快。您可以使用true那里的文字来比较每个元素。您甚至可以展开循环或执行不安全的代码技巧。

