简体   繁体   中英

c# linq if item is in list and get matching items from list

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)) { }

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

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:

查找分组结果

Then just extract cats such as

var cats = sortedbyDogs[false].ToList()

列出猫串

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

在此处输入图片说明

Then to get our cats, here is the code:

sorted["cat"].ToList()

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