本文介绍了如何获取列表的包含字符串的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个列表<串>
和我检查它是否包含一个字符串:
I have a List<string>
and i check if it contains a string:
if(list.Contains(tbItem.Text))
和如果这是真的我这样做:
and if it's true I do this:
int idx = list.IndexOf(tbItem.Text)
但如果我有例如2相同的字符串?我希望得到所有具有此字符串,然后通过它使用的foreach循环索引。我怎样才能做到这一点。
But what if I have for example 2 same strings? I want to get all the indexes that have this string and then use foreach to loop through it. How I can do that?
推荐答案
假设列表的是列表与LT?;字符串>
:
IEnumerable<int> allIndices = list.Select((s, i) => new { Str = s, Index = i })
.Where(x => x.Str == tbItem.Text)
.Select(x => x.Index);
foreach(int matchingIndex in allIndices)
{
// ....
}
这篇关于如何获取列表的包含字符串的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!