0

I have an array of string and I want to get back from it a filtered array that contains only those strings that match the searched string.

string[] myValues = {"School.Report1", "School.Report2", "School.Report3", "House.Report1", "House.Report2"};
string myFilter = "School";
string[] filteredValues = myValues.Filter(myFilter); // or something similar

filteredValues must contains only: "School.Report1", "School.Report2", "School.Report3".

-- EDIT --

I prefer a non-LINQ approach if possibile. Otherwise I know that this question can be answered with the solution proposed here: filter an array in C#.

5
  • possible duplicate of filter an array in C# Commented Jul 15, 2015 at 7:35
  • @Sayse Yes, but the proposed solution that doesn't use LINQ, is a foreach loop with the comparison inside. I want to know if there's a more elegant and concise way to do it without LINQ. Commented Jul 15, 2015 at 7:39
  • Can it contain School1.Report1 Commented Jul 15, 2015 at 7:40
  • @CheshireCat: You haven't mentioned that you can't use LINQ, why? Commented Jul 15, 2015 at 7:41
  • You should show what you have tried, that was just the first duplicate I found but there are plenty of duplicates around. and most of them use the method you described so I'm not sure what the actual question is here Commented Jul 15, 2015 at 7:41

2 Answers 2

2

If you can't use LINQ you can still use Array.FindAll:

string[] filteredValues = Array.FindAll(myValues, s => s.Contains(myFilter)); 

or maybe you want to keep only all strings which first token(separated by dot) is School:

string[] filteredValues = Array.FindAll(myValues, s => s.Split('.')[0] == myFilter);
Sign up to request clarification or add additional context in comments.

Comments

0

One possible answer is to make an IComparer that sorts the array by the matching value (if it contains filter return 1 else return 0) then find the first item outside the filter and make another array with the values up the one before that point.

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.