C# 检查列表是否包含包含字符串的元素并获取该元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18767302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if list contains element that contains a string and get that element
提问by Dimitris Iliadis
While searching for an answer to this question, I've run into similar ones utilizing LINQ but I haven't been able to fully understand them (and thus, implement them), as I'm not familiarized with it. What I would like to, basically, is this:
在寻找这个问题的答案时,我遇到了类似的使用 LINQ 的问题,但我无法完全理解它们(并因此实现它们),因为我不熟悉它。基本上,我想要的是:
- Check if any element of a list contains a specific string.
- If it does, get that element.
- 检查列表的任何元素是否包含特定字符串。
- 如果是,请获取该元素。
I honestly don't know how I would go about doing that. What I can come up with is this (not working, of course):
老实说,我不知道我会怎么做。我能想到的是这个(当然不工作):
if (myList.Contains(myString))
string element = myList.ElementAt(myList.IndexOf(myString));
I know WHY it does not work:
我知道为什么它不起作用:
myList.Contains()
does not returntrue
, since it will check for if a whole element of the list matches the string I specified.myList.IndexOf()
will not find an occurrence, since, as it is the case again, it will check for an element matching the string.
myList.Contains()
不返回true
,因为它将检查列表的整个元素是否与我指定的字符串匹配。myList.IndexOf()
不会找到匹配项,因为它会再次检查匹配字符串的元素。
Still, I have no clue how to solve this problem, but I figure I'll have to use LINQ as suggested in similar questions to mine. That being said, if that's the case here, I'd like for the answerer to explain to me the use of LINQ in their example (as I said, I haven't bothered with it in my time with C#). Thank you in advance guys (and gals?).
尽管如此,我仍然不知道如何解决这个问题,但我认为我必须按照与我的类似问题中的建议使用 LINQ。话虽如此,如果是这种情况,我希望回答者向我解释在他们的示例中使用 LINQ(正如我所说,我在使用 C# 的时候并没有为此烦恼)。提前谢谢你们(和女孩?)。
EDIT: I have come up with a solution; just loop through the list, check if current element contains the string and then set a string equal to the current element. I'm wondering, though, is there a more efficient way than this?
编辑:我想出了一个解决方案;只需遍历列表,检查当前元素是否包含字符串,然后设置一个等于当前元素的字符串。不过,我想知道还有比这更有效的方法吗?
string myString = "bla";
string element = "";
for (int i = 0; i < myList.Count; i++)
{
if (myList[i].Contains(myString))
element = myList[i];
}
采纳答案by Dave Bish
You should be able to use Linq here:
您应该可以在这里使用 Linq:
var matchingvalues = myList
.Where(stringToCheck => stringToCheck.Contains(myString));
If you simply wish to return the first matching item:
如果您只想返回第一个匹配项:
var match = myList
.FirstOrDefault(stringToCheck => stringToCheck.Contains(myString));
if(match != null)
//Do stuff
回答by Chris
string result = myList.FirstOrDefault(x => x == myString)
if(result != null)
{
//found
}
回答by McKay
for (int i = 0; i < myList.Length; i++)
{
if (myList[i].Contains(myString)) // (you use the word "contains". either equals or indexof might be appropriate)
{
return i;
}
}
Old fashion loops are almost always the fastest.
旧时尚循环几乎总是最快的。
回答by p.s.w.g
You could use Linq's FirstOrDefault
extension method:
您可以使用 Linq 的FirstOrDefault
扩展方法:
string element = myList.FirstOrDefault(s => s.Contains(myString));
This will return the fist element that contains the substring myString
, or null
if no such element is found.
这将返回包含 substring 的第一个元素myString
,或者null
如果没有找到这样的元素。
If all you need is the index, use the List<T>
class's FindIndex
method:
如果您只需要索引,请使用List<T>
该类的FindIndex
方法:
int index = myList.FindIndex(s => s.Contains(myString));
This will return the the index of fist element that contains the substring myString
, or -1
if no such element is found.
这将返回包含 substring 的第一个元素的索引myString
,或者-1
如果没有找到这样的元素。
回答by Alessandro D'Andria
If you want a list of strings containing your string:
如果你想要一个包含你的字符串的字符串列表:
var newList = myList.Where(x => x.Contains(myString)).ToList();
Another option is to use Linq FirstOrDefault
另一种选择是使用 Linq FirstOrDefault
var element = myList.Where(x => x.Contains(myString)).FirstOrDefault();
Keep in mind that Contains
method is case sensitive.
请记住,该Contains
方法区分大小写。
回答by userda
The basic answer is: you need to iterate through loop and check any element contains the specified string. So, let's say the code is:
基本答案是:您需要遍历循环并检查任何包含指定字符串的元素。所以,让我们说代码是:
foreach(string item in myList)
{
if(item.Contains(myString))
return item;
}
The equivalent, but terse, code is:
等效但简洁的代码是:
mylist.Where(x => x.Contains(myString)).FirstOrDefault();
Here, x is a parameter that acts like "item" in the above code.
这里,x 是一个参数,其作用类似于上述代码中的“item”。
回答by devavx
To keep it simple use this;
为了保持简单,请使用它;
foreach(string item in myList)//Iterate through each item.
{
if(item.Contains("Search Term")//True if the item contains search pattern.
{
return item;//Return the matched item.
}
}
Alternatively,to do this with for loop,use this;
或者,要使用 for 循环执行此操作,请使用 this;
for (int iterator = 0; iterator < myList.Count; iterator++)
{
if (myList[iterator].Contains("String Pattern"))
{
return myList[iterator];
}
}
回答by Nithin Nayagam
you can use
您可以使用
var match=myList.Where(item=>item.Contains("Required String"));
foreach(var i in match)
{
//do something with the matched items
}
LINQ provides you with capabilities to "query" any collection of data. You can use syntax like a database query (select, where, etc) on a collection (here the collection (list) of strings).
LINQ 为您提供了“查询”任何数据集合的功能。您可以在集合(这里是字符串的集合(列表))上使用类似数据库查询(选择、位置等)的语法。
so you are doing like "get me items from the list Where it satisfies a given condition"
所以你正在做“从满足给定条件的列表中获取我的项目”
inside the Where you are using a "lambda expression"
在您使用“lambda 表达式”的地方
to tell briefly lambda expression is something like (input parameter => return value)
简单地说 lambda 表达式类似于(输入参数 => 返回值)
so for a parameter "item", it returns "item.Contains("required string")" . So it returns true if the item contains the string and thereby it gets selected from the list since it satisfied the condition.
所以对于参数“item”,它返回“item.Contains(“required string”)”。因此,如果该项目包含字符串并因此从列表中选择它,则它返回 true,因为它满足条件。
回答by Ali
Many good answers here, but I use a simple one using Exists, as below:
这里有很多很好的答案,但我使用了一个简单的Exists,如下所示:
foreach (var setting in FullList)
{
if(cleanList.Exists(x => x.ProcedureName == setting.ProcedureName))
setting.IsActive = true; // do you business logic here
else
setting.IsActive = false;
updateList.Add(setting);
}
回答by Pawel Czapski
I have not seen bool option in other answers so I hope below code will help someone.
我还没有在其他答案中看到 bool 选项,所以我希望下面的代码可以帮助某人。
Just use Any()
只需使用 Any()
string myString = "test";
bool exists = myList
.Where(w => w.COLUMN_TO_CHECK.Contains(myString)).Any();