C#Determing在一个字符串数组的任何元素是否包含任何地方给定的字符串 [英] C# Determing whether any element in a string array contains a given string anywhere

查看:303
本文介绍了C#Determing在一个字符串数组的任何元素是否包含任何地方给定的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串数组:

string[] Animals = {"Cat", "Dog", "Fish"};

然后我要确定哪些元素包含序列是,并返回整个元素;在这种情况下,鱼

I then want to determine which element contains the sequence "is" and return that entire element; in this case "fish"

如果我想找到GH,它不存在于列表中存在,所以它应该返回的第一个元素,在这种情况下,猫

If I want to find "gh", it does not exist in the list, so it should return the first element, in this case "Cat"

我试过这个LINQ code,但我不认为我做的拉姆达的部分权利。

I've tried this linq code, but i don't think I'm doing the lambda part right.

int index = Animals.Where(x => x.IndexOf("is") >= 0).First().IndexOf("is")
string result = index > 0 ? Animals[index] : Animals[0];

这code抛出这个错误:

This code throws this error:

Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: value

我想我接近,我只是似乎我没有得到它。

I think I'm close, I just can't seem to get it.

这方法显然也不是省油的证明,它应该返回的是第一个实例可能是有问题的。我的潜力列表相当小,指数字始终是独一无二的。

This method obviously isn't fool proof, it should return the first instance of "is" which could be problematic. My potential list is fairly small and the index word is always unique.

推荐答案

试试这个:

string result = Animals.FirstOrDefault(x => x.Contains("is")) ?? Animals.First();

(如果该数组包含任何元素,这将会失败;您想在这种情况下做什么做的你可以尝试 FirstOrDefault 回退前pression作为好 - 这将返回如果序列为空)

(This will fail if the array contains no elements; what do you want to do in this case? You could try FirstOrDefault for the fallback expression as well - this will return null if the sequence is empty.)

由于您的要求,您发布的code有2个问题:

Given your requirements, the code you posted has 2 issues:


  1. 它使用 Enumerable.First ,这将抛出一个空序列,即如果项目不存在,原来的predicate相匹配。
  2. 异常
  3. 您正在使用的第二个语句的索引是的,是子在第一次查询的结果,不可以的结果在原始索引<索引/ em>的数组。因此,它是没有意义使用该号码来索引原始数组。

  1. It uses Enumerable.First, which will throw an exception on an empty sequence i.e. if no item exists that matches the original predicate.
  2. The index you are using in the the second statement is the index of the "is" substring in the result of the first query, not the index of the result in the original array. Consequently, it does not make sense to use that number to index the original array.

这篇关于C#Determing在一个字符串数组的任何元素是否包含任何地方给定的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆