Check if list contains element that contains a string and get that element

前端 未结 12 2511
抹茶落季
抹茶落季 2020-12-07 10:39

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

12条回答
  •  庸人自扰
    2020-12-07 11:11

    You could use Linq's FirstOrDefault extension method:

    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.

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

    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.

提交回复
热议问题