【问题标题】:How to get the indexes of list that contains a string如何获取包含字符串的列表的索引
【发布时间】:2013-03-08 23:59:23
【问题描述】:

我有一个List<string>,我检查它是否包含一个字符串:

if(list.Contains(tbItem.Text))

如果是真的,我会这样做:

int idx = list.IndexOf(tbItem.Text)

但是如果我有两个相同的字符串呢?我想获取所有具有此字符串的索引,然后使用 foreach 循环遍历它。我该怎么做?

【问题讨论】:

标签: c# winforms list


【解决方案1】:

假设 listList<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)
{
    // ....
}

【讨论】:

  • 感谢您的出色工作.. 我假设其他答案也有效,所以谢谢大家..
【解决方案2】:

这个怎么样:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-17
    • 2020-09-23
    • 2015-06-18
    • 2017-03-13
    • 1970-01-01
    • 2011-03-31
    相关资源
    最近更新 更多