检查字符串是否包含任何字符串数组值,然后获取子字符串

这可能是这个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 表达式吗?我试过我失败了。


谢谢你们


慕桂英3389331
浏览 155回答 3
3回答

慕尼黑的夜晚无繁华

用于IndexOf了解 item 是否存在,address如果存在则返回其后面的字符串:var result = from item in streetType&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;let index = address.IndexOf(item)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;where index != -1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;select address.SubString(0, index);

慕的地10843

一种方法是简单地列出列表中Split的每个地址streetType,然后index[0]从结果数组中获取第一项(at):addresses&nbsp;=&nbsp;addresses &nbsp;&nbsp;&nbsp;&nbsp;.Select(address&nbsp;=>&nbsp;address.Split(streetTypes.ToArray(),&nbsp;StringSplitOptions.None)[0]) &nbsp;&nbsp;&nbsp;&nbsp;.ToList();

ABOUTYOU

我可能倾向于做这样的事情:string[] markers = "ave avenue pkwy".Split();string address = "1st nice ave 1st floor";var result = markers&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Select((marker, index) => new&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; markerIndex = index,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; addressPosition = address.IndexOf(marker)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .FirstOrDefault(x => x.addressPosition != -1);// returns { markerIndex = 0, addressPosition = 9 }Thenresult是一个对象,要么为null(如果未找到标记),要么是包含两者的对象markerIndex,它告诉您首先找到哪个标记,并addressPosition告诉您找到标记字符串的字符。
打开App,查看更多内容
随时随地看视频慕课网APP