LinQ WHERE string.Contains or string.IndexOf?

后端 未结 4 405
暗喜
暗喜 2020-12-06 14:35

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


        
相关标签:
4条回答
  • 2020-12-06 15:06
    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.

    0 讨论(0)
  • 2020-12-06 15:06

    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); 
    
    0 讨论(0)
  • 2020-12-06 15:07

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

    0 讨论(0)
  • 2020-12-06 15:08

    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.

    0 讨论(0)
提交回复
热议问题