LINQ如何包含工作 [英] How does LINQ contains work
问题描述
我了解如何使用LINQ,因此语法在这里并不重要. LINQ如何精确地穿透包含",并且背景中发生了什么?我了解它会找到包含您要查找的单词的所有元素,但是会找到包含多个未包含的单词的结果吗?例如,我在数据库中有一个用于输入名称的行,如果使用包含,我就能找到
I understand how to use LINQ so the syntax is not important here. How exactly does LINQ interpenetrate "contains" and what is going on in the background? I understand that it finds all the elements that have the word you are looking for but will it find a result with multiple words that are not all contained? For example I have a row in a database for a name and if i use contains will I be able to find my person with
Contains("James Bar")
如果真名是James foo Bar
If the real name is James foo Bar
还是查询只是寻找
where name like '%James bar%'
不返回结果
推荐答案
Here we go --- check it out via reference source: Contains calls IndexOf with a greater equal comparison and that calls an overloaded IndexOf method. hth
[Pure]
public bool Contains( string value ) {
return ( IndexOf(value, StringComparison.Ordinal) >=0 );
}
[Pure]
public int IndexOf(String value, StringComparison comparisonType) {
return IndexOf(value, 0, this.Length, comparisonType);
}
[Pure]
[System.Security.SecuritySafeCritical]
public int IndexOf(String value, int startIndex, int count, StringComparison comparisonType) {
// Validate inputs
if (value == null)
throw new ArgumentNullException("value");
if (startIndex < 0 || startIndex > this.Length)
throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
if (count < 0 || startIndex > this.Length - count)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Count"));
Contract.EndContractBlock();
switch (comparisonType) {
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.None);
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase);
case StringComparison.InvariantCulture:
return CultureInfo.InvariantCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
return CultureInfo.InvariantCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase);
case StringComparison.Ordinal:
return CultureInfo.InvariantCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.Ordinal);
case StringComparison.OrdinalIgnoreCase:
if (value.IsAscii() && this.IsAscii())
return CultureInfo.InvariantCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase);
else
return TextInfo.IndexOfStringOrdinalIgnoreCase(this, value, startIndex, count);
default:
throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), "comparisonType");
}
}
这篇关于LINQ如何包含工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!