Home > database >  Return all values from an array that contains the value from another array
Return all values from an array that contains the value from another array

Time:07-20

I am trying to return an array of all the values from an array that contain values from another array.

 string[] files = new string[] 
 {
      "1.mp3", "2.mp3", "1.mp4", "2.txt", "4.wav", "5.ini"
 }

 string[] filters = new string[]
 {
     ".mp3", ".mp4", ".wav"
 }

I want to return the values that only contain the text in the filters.

I know how to get the elements using a single reference such as;

 string[] filtered = Array.FindAll(files, c => c.Contains(".mp3");

Is there a way to use contains with multiple values?

I've also tried

files.Intersect(filters).Any(); 

Which just returned all the results in files. Not sure what I am doing wrong.

CodePudding user response:

files.Where(file => filters.Any(filter => file.Contains(filter)));

CodePudding user response:

Create a new List, lists are superior to arrays since you do not need to know how many elements exist before creating it.

Then do a foreach loop for one array, and put another foreach loop inside it for the other array.

Then add an if statement looking for matching substrings. If it matches, add it to your List.

Something like this:

List<string> matches = new List<string>();
 
 foreach(string file in files){
    foreach(string filter in filters){
        if(file.Contains(filter)){
            matches.Add(file);
        }
    }
 }
  • Related