私は持っています、List<string>
そして私はそれが文字列を含んでいるかどうかをチェックします:
if(list.Contains(tbItem.Text))
そしてそれが本当なら私はこれをします:
int idx = list.IndexOf(tbItem.Text)
しかし、たとえば2つの同じ文字列がある場合はどうなりますか?この文字列を持つすべてのインデックスを取得し、foreachを使用してループします。どうすればそれができますか?
リストがList<string>
:であると仮定します
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)
{
// ....
}
これはどう:
List<int> matchingIndexes = new List<int>();
for(int i=0; i<list.Count; i++)
{
if (item == tbItem.Text)
matchingIndexes.Add(i);
}
//Now iterate over the matches
foreach(int index in matchingIndexes)
{
list[index] = "newString";
}
または、linqを使用してインデックスを取得します
int[] matchingIndexes = (from current in list.Select((value, index) => new { value, index }) where current.value == tbItem.Text select current.index).ToArray();