简体   繁体   中英

LinQ WHERE string.Contains or string.IndexOf?

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...

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.

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.

If you want to test whether o.Name contains a stringToCheck then:

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.

您正在检查集合元素o.ToLower()我假设您必须检查其名称o.Name.ToLower()

If you want to check whether o.Name contains some string from the stringsToCheck , I would suggest to use LinqKit and build the query with 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM