3

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)) { }
2
  • try this: var movies = _db.Movies.Where(p => p.Genres.Intersect(listOfGenres).Any()); stackoverflow.com/questions/10667675/… Commented May 27, 2019 at 15:28
  • If it's a list of strings, then I think List<string> results = myList.Where(item => item.ToLower.Contains("dog"); would do the trick. Commented May 27, 2019 at 15:28

3 Answers 3

6

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()));
Sign up to request clarification or add additional context in comments.

Comments

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();
}

Comments

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.