首页 > 解决方案 > 检查字符串是否包含任何字符串数组值,然后获取子字符串

问题描述

这可能是这个SO Question的一个子问题。我想根据字符串或列表数组检查字符串。例子

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

目的是去除大道后的额外地址详细信息,csv 文件包含所有 USPS 接受的街道类型。

这就是我现在所拥有的

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

我一直在寻找如何解决这个问题的几个小时,然后我遇到了 SO 问题,这正是我想要的,但我需要获取子字符串以进行剥离。

如果有一个 linq 查询,那就太棒了。我能想到的唯一方法是使用 foreach 和 inner if。

数组值示例

更新:

这是我的答案,我忘了提到数组查找需要匹配地址字符串中的确切字符串。我最终使用了正则表达式。这是@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);

有人可以将其转换为 lambda 表达式吗?我试过我失败了。

谢谢你们

标签: c#arraysstring

解决方案


用于IndexOf了解 item 是否存在,address如果存在则返回其后面的字符串:

var result = from item in streetType
             let index = address.IndexOf(item)
             where index != -1
             select address.SubString(0, index);

推荐阅读