1

我有一个列表项

List<string> xmlValue = new List<string>();

在此我有 Item{"English","Spanish","French","Hindi","English","English"} 我需要搜索所有英文项目及其Index(item index). 我写了下面的代码,它只返回一项的索引。如何也可以获得下一项的索引。

    string search = "English";
    int index = xmlValue.Select((item, i) => new { Item = item, Index = i })
    .First(x => x.Item == search).Index;
4

2 回答 2

4
List<string> xmlValue = new List<string>() 
                 {"English", "Spanish", "French", "Hindi", "English", "English"};

string search = "English";

int[] result = xmlValue.Select((b, i) => b.Equals(search) ? i : -1)
                       .Where(i => i != -1).ToArray();
于 2012-07-02T10:58:22.287 回答
1

在这种情况下,我会选择不使用 LINQ 扩展方法并使用“老式”循环:

string search = "English";

var foundIndices = new List<int>(xmlValue.Count);
for (int i = 0; i < xmlValue.Count; i++) {
    if (xmlValue[i] == search) {
        foundIndices.Add(i);
    }
}

在我看来,它只是更具可读性;此外,该foundIndices列表永远不会包含任何不需要的值。

于 2012-07-02T11:03:40.580 回答