【问题标题】:List Index Search列表索引搜索
【发布时间】:2012-07-02 10:55:46
【问题描述】:

我有一个列表项

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

在这我有物品{"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;

【问题讨论】:

  • 您希望将索引存储在哪里?在您的int 变量index 中,您一次只能存储一个索引。

标签: c#


【解决方案1】:
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();

【讨论】:

  • 感谢 Nikhil,回复很快。
  • @MahmoudGamal:我不确定他是否只想要前 两个 索引。请注意他在整个问题中如何不使用单个复数形式,即使在需要的地方也是如此。因此,我推测他正在寻找所有后续项目的索引,而不仅仅是下一个项目。
【解决方案2】:

在这种情况下,我会选择不使用 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 列表永远不会包含任何不需要的值。

【讨论】:

  • @Reniuz:那是品味问题。这个循环 IMO 清楚地显示了正在查找的内容和添加的内容,而对于 labmda 表达式,必须执行一些带有无效索引的技巧,这些技巧后来被过滤掉。更短并不总是更好:-)
  • @christopherPeter:创建一个包含大量项目的列表,并在测量时间的同时运行两个解决方案。 Thisthisthis 可以提供起点。
猜你喜欢
  • 2014-10-18
  • 1970-01-01
  • 2018-05-06
  • 2015-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多