1

If my list contains: english cat, french cat, japanese dog, spanish dog

and I have an item: dog

Not only do I want to see if the list contains my item, but return the items that match, so I would expect: japanese dog, spanish dog

I have got as far as seeing if the item is in the list using the following code:

if (myList.Any(myItem.ToLower().Contains)) { }
ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
  • try this: var movies = _db.Movies.Where(p => p.Genres.Intersect(listOfGenres).Any()); https://stackoverflow.com/questions/10667675/linq-where-list-contains-any-in-list – raBinn May 27 '19 at 15:28
  • If it's a list of strings, then I think `List results = myList.Where(item => item.ToLower.Contains("dog");` would do the trick. – StackLloyd May 27 '19 at 15:28

3 Answers3

5

I think you are looking for something like this, using the where clause:

string filter = "dog";
IEnumerable<string> filteredItems = myList.Where(m => m.ToLower().Contains(filter.ToLower()));
Pinx0
  • 1,248
  • 17
  • 28
4
var myList = new List<string>() { " japanese dog", "spanish dog", "english cat", "french cat" };
var dog = "Dog";

if (myList.Any(t=>t.Contains(dog.ToLower()))) {
    var result = myList.Where(t => t.Contains(dog.ToLower())).ToList();
}
Jones
  • 1,480
  • 19
  • 34
Basil Kosovan
  • 888
  • 1
  • 7
  • 30
1

I like to use regex and to do that such as for dogs:

var animals = new List<string>() 
               { "japanese dog", "spanish dog", "english cat", "french cat" };

var dogs = animals.Where(type => Regex.IsMatch(type, "dog", RegexOptions.IgnoreCase))
                  .ToList();

// Returns {"japanese dog",  "spanish dog" } 

Why Regex you may ask, because its flexible and powerful...let me show:

Let us do some more advance linq work by having them sorted using the ToLookup extension and regex such as

var sortedbyDogs 
            = animals.ToLookup(type => Regex.IsMatch(type, "dog", RegexOptions.IgnoreCase));

which is grouped in memory like this:

To lookup grouping result

Then just extract cats such as

var cats = sortedbyDogs[false].ToList()

List string of cats

then pass in true for dogs.


But why split it by a boolean, what if there are more animals? Lets add a lemur to the list such as … "french cat", "Columbian Lemur" }; we do this:

var sorted = animals.ToLookup(type => Regex.Match(type, 
                                                  "(dog|cat|lemur)", 
                                                  RegexOptions.IgnoreCase).Value);

enter image description here

Then to get our cats, here is the code:

sorted["cat"].ToList()

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122