This may be a sub-question to this SO Question. I want to check the string against an array of string or list. Example
string address = "1st nice ave 1st floor";
//For now, I'm getting the list from a text file but could move to use an EF
List<string> streetType = File.ReadLines(AppDomain.CurrentDomain.BaseDirectory + @"streetType.csv")
.Where(x => x.Length > 0)
.Select(y => y.ToLowerInvariant())
.ToArray();
the purpose is to strip the extra address details after the avenue, the csv file contains all USPS accepted street type.
This is what I have now
//this only returns boolean value, I got this from the SO above
streetType.Any(testaddress.ToLower().Contains);
//I also have this
Array.Exists<string>(streetType, (Predicate<string>)delegate (string s)
{
return testaddress.IndexOf(s, StringComparison.OrdinalIgnoreCase) > -1;
});
I've been looking for hours how to resolve this then I came across the SO question which is exactly what I also want but I need to get the substring to for stripping.
If there's a linq query, that would be awesome. The only way I can think of doing this is with foreach and inner if.
Example of the array values
- ave
- avenue
- pkwy
Update:
Here is my answer, I forgot to mention that the array lookup needs to match the exact string from the address string. I ended up using regex. This is the expanded/modified answer of @giladGreen.
var result = from item in streetTypes
let index = Regex.Match(address.ToLowerInvariant(), @"\b" + item.ToLowerInvariant() + @"\b")
where index.Success == true
select address.ToLowerInvariant().Substring(0, index.Index + item.Length);
Can somebody convert this to lambda expression? I tried I failed.
Thank you all