C# LinQ WHERE string.Contains 还是 string.IndexOf?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14346961/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:31:58  来源:igfitidea点击:

LinQ WHERE string.Contains or string.IndexOf?

c#.netlinq

提问by Seb

I need to write something that would give the same result as:

我需要写一些与以下结果相同的东西:

var result = collection.Where( o => o.Name.IndexOf( "some_string2" ) != -1 || o.Name.IndexOf( "some_string_2" ) != -1 || o.Name.IndexOf( "some_string3" ) != -1 )

Where the amount and values of the strings to check for (some_string_1, 2 and 3) are unknown (coming from DB), so something more generic...

要检查的字符串的数量和值(some_string_1、2 和 3)未知(来自 DB),所以更通用的东西......

I tried the following, but failed...

我尝试了以下方法,但失败了...

var stringsToCheck = someCommaSeparatedStrings.ToLower().Split( ',' ).ToList();
var result = collection.Where( o => stringsToCheck.Contains( o.ToLower() ) );

In other words, I need to retrieve all the objects from a collection which names contain some specific strings.

换句话说,我需要从名称包含一些特定字符串的集合中检索所有对象。

采纳答案by Servy

var result = collection.Where(item => stringsToCheck.Any(stringToCheck => 
    item.Name.Contains(stringToCheck)));

Read in English this is: give me all of the items in the collection where, of all of the strings to check one of them is a substring of the string in the collection.

用英语阅读这是:给我集合中的所有项目,其中所有要检查的字符串中的一个是集合中字符串的子字符串。

回答by Hamlet Hakobyan

You are checking the collections element o.ToLower()i assume you must check for its name o.Name.ToLower().

您正在检查 collections 元素,o.ToLower()我认为您必须检查其名称o.Name.ToLower()

回答by mipe34

If you want to check whether o.Namecontains some stringfrom the stringsToCheck, I would suggest to use LinqKitand build the query with PredicateBuilder.

如果你想检查是否o.Name包含一些string来自stringsToCheck,我建议使用LinqKit并使用PredicateBuilder.

var predicate = PredicateBuilder.False<TypeOfYourObject>();
var stringsToCheck = someCommaSeparatedStrings.ToLower().Split( ',' ).ToList();

foreach(var str in stringsToCheck)
{
     var tmp = str; 
     predicate = predicate.Or(o=> o.Name.IndexOf(tmp) != -1);
} 
resultQuery = collection.Where(predicate); 

回答by Chamila Chulatunga

If you want to test whether o.Namecontains a stringToCheckthen:

如果要测试是否o.Name包含stringToCheck则:

var result = collection.Where( o => stringsToCheck.Any(a => o.Name.Contains(a)));

If you only need to test for equality, then:

如果您只需要测试相等性,则:

var result = collection.Where( o => stringsToCheck.Contains(o.Name));

Note: if you need to apply case normalisation then ToLower()should be applied accordingly.

注意:如果您需要应用案例规范化,ToLower()则应相应地应用。