c# - 检查字符串是否包含任何字符串数组值,然后获取子字符串
问题描述
这可能是这个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。
数组值示例
- 大道
- 大街
- pkwy
更新:
这是我的答案,我忘了提到数组查找需要匹配地址字符串中的确切字符串。我最终使用了正则表达式。这是@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 表达式吗?我试过我失败了。
谢谢你们
解决方案
用于IndexOf
了解 item 是否存在,address
如果存在则返回其后面的字符串:
var result = from item in streetType
let index = address.IndexOf(item)
where index != -1
select address.SubString(0, index);
推荐阅读
- flutter - 控制台在运行时给出未定义的名称上下文(颤动)
- java - 你如何使用java读取一个太大的excel文件?
- azure - 当租户根级别的其他策略被拒绝时,将资源创建位置策略分配给订阅
- coreml - 没有先验层和 softmax 层的 YOLACT onnx 的 xrunc coreml 模型错误
- android - firebase 类 Lio/grpc/internal/GrpcUtil 中没有 Z 类型的静态字段 IS_RESTRICTED_APPENGINE;或其超类错误
- json - 在 Python Flask 应用程序中使用外部 API 时如何解决无返回错误?
- jenkins - 使用 Jenkins 的 Artifactory depoyment 失败
- import - 无法导入任何非标准库python3
- java - 在 DB2 中执行更新查询的 Java 程序显示 SqlSyntaxErrorException
- servlets - Httpservletrequest.authenticate() 方法不发送重定向到登录页面