4

私は持っています、List<string>そして私はそれが文字列を含んでいるかどうかをチェックします:

if(list.Contains(tbItem.Text))

そしてそれが本当なら私はこれをします:

int idx = list.IndexOf(tbItem.Text)

しかし、たとえば2つの同じ文字列がある場合はどうなりますか?この文字列を持つすべてのインデックスを取得し、foreachを使用してループします。どうすればそれができますか?

4

2 に答える 2

13

リスト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)
{
    // ....
}
于 2013-03-09T00:04:51.200 に答える
1

これはどう:

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();
于 2013-03-09T00:03:08.113 に答える