So I'm working on a filter for a resource list and one of the filters is the Name property(string).
As a(dumb) example : resource name is "Big,Red/Square Table" and the filter is "Table Red", it should be a valid resource
This is what I could come up with using the little time I had:
static void ApplyNameFilter(ref ApplicationViewModel model, string filter)
{
if (string.IsNullOrEmpty(filter) || filter == "") return;
char[] separators = {' ', ',', '.', '/', '\\', '|', '_', '-'};
var validResources = new List<ResourceModel>();
foreach (var resource in model.ResourcesViewModel.Resources)
{
var filterSubstrings =
filter
.ToLower()
.Split(separators)
.ToList();
var resourceSubstrings =
resource.Name
.ToLower()
.Split(separators)
.ToList();
resourceSubstrings.ForEach(substring => {
if (filterSubstrings.Contains(substring))
filterSubstrings.RemoveAll(sub => sub == substring);
});
if (filterSubstrings.Count == 0)
validResources.Add(resource);
}
model.ResourcesViewModel.Resources = validResources;
}
Should I take a different approach for this?
EDIT: Ended up going with this until I figure out RegEx
static void ApplyNameFilter(ref ApplicationViewModel model, string filter)
{
if (string.IsNullOrEmpty(filter)) return;
char[] separators = {' ', ',', '.', '/', '\\', '|', '_', '-'};
var filterSubstrings =
filter
.ToLower()
.Split(separators)
.ToList();
var validResources = model.ResourcesViewModel.Resources
.Where(resource => filterSubstrings.All(fs => resource.Name.ToLower().Contains(fs)))
.ToList();
model.ResourcesViewModel.Resources = validResources;
}
regexsolution - you'll definitely have more concise code. There are other ways to skin this cat, but you'd have to be digging back to your comp sci 101 past and thinking about dynamic programming (at least that's what's coming to my mind, LOL). Single responsibility principle based approach also might make your life a lesser hell, here, as well. In both theregexand non-regex approaches, try to leverage an immutability based approach. You're going to really appreciate that you didn't change things in-place, later on.$"{your variable here}regex expression here"- that's just a very raw, off-the-cuff example. I strongly suggest googling regex, you are not going to need a very complex regex, for what you are trying to do..Intersector.All, which is immutable and also, almost gives you the solution. e.g:filterSubstrings.Intersect(resourceSubstrings).Count() == filterSubstrings.CountORfilterSubstrings.All(fs => resourceSubstrings.Contains(fs)). Also you don't need to compute thefilterSubstringin every iteration, they do not change. so put them out of your loop.