检查列表是否包含包含包含字符串的元素并获取该元素

时间:2020-11-26 01:37:34

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遇到了类似的问题,但是我没有完全理解它们(因此,实现它们),因为我不熟悉它。基本上,我想说的是:

  1. Check if any element of a list contains a specific string.
  2. 检查列表中的任何元素是否包含特定的字符串。
  3. If it does, get that element.
  4. 如果有,就得到那个元素。

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 return true, since it will check for if a whole element of the list matches the string I specified.
  • contains()不会返回true,因为它将检查列表的整个元素是否与我指定的字符串匹配。
  • myList.IndexOf() will not find an occurrence, since, as it is the case again, it will check for an element matching the string.
  • 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];
}

9 个解决方案

#1


112  

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

#2


16  

The basic answer is You need to iterate through loop and check any element contains the specified string. So, Lets say 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 parameter that acts like item in above code.

这里,x是一个参数,它的作用类似于上面代码中的项。

#3


7  

string result = myList.FirstOrDefault(x => x == myString)
if(result != null)
{
  //found
}

#4


6  

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.

旧的时尚圈几乎总是最快的。

#5


3  

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 method是区分大小写的。

#6


2  

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.

这将返回包含子字符串myString的第一个元素,如果没有找到该元素,则返回null。

If all you need is the index, use the List<T> class's FindIndex method:

如果你只需要索引,使用列表 类的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.

这将返回包含子字符串myString的拳头元素的索引,如果找不到此类元素,则返回-1。

#7


1  

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为您提供了“查询”任何数据集合的功能。您可以在集合(这里是字符串的集合(列表)上使用类似于数据库查询(select, where, etc)的语法。

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”。包含(“需要字符串”)”。因此,如果项包含字符串,则返回true,因此它从列表中选择,因为它满足条件。

#8


1  

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循环执行此操作,请使用这个;

    for (int iterator = 0; iterator < myList.Count; iterator++)
    {
        if (myList[iterator].Contains("String Pattern"))
        {
            return myList[iterator];
        }
    }

#9


0  

many good answers here , but i use a simple one as below ,using Exists

这里有很多很好的答案,但是我使用一个简单的答案如下,use exist

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

#1


112  

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

#2


16  

The basic answer is You need to iterate through loop and check any element contains the specified string. So, Lets say 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 parameter that acts like item in above code.

这里,x是一个参数,它的作用类似于上面代码中的项。

#3


7  

string result = myList.FirstOrDefault(x => x == myString)
if(result != null)
{
  //found
}

#4


6  

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.

旧的时尚圈几乎总是最快的。

#5


3  

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 method是区分大小写的。

#6


2  

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.

这将返回包含子字符串myString的第一个元素,如果没有找到该元素,则返回null。

If all you need is the index, use the List<T> class's FindIndex method:

如果你只需要索引,使用列表 类的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.

这将返回包含子字符串myString的拳头元素的索引,如果找不到此类元素,则返回-1。

#7


1  

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为您提供了“查询”任何数据集合的功能。您可以在集合(这里是字符串的集合(列表)上使用类似于数据库查询(select, where, etc)的语法。

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”。包含(“需要字符串”)”。因此,如果项包含字符串,则返回true,因此它从列表中选择,因为它满足条件。

#8


1  

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循环执行此操作,请使用这个;

    for (int iterator = 0; iterator < myList.Count; iterator++)
    {
        if (myList[iterator].Contains("String Pattern"))
        {
            return myList[iterator];
        }
    }

#9


0  

many good answers here , but i use a simple one as below ,using Exists

这里有很多很好的答案,但是我使用一个简单的答案如下,use exist

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