在c#中获取列表中重复项的索引
我正在寻找一种方法来从列表中的关键字搜索获取列表中所有元素的索引。 例如,我的列表有:
Hello World Programming Rocks Hello Hello World I love C# Hello
现在从这个字符串列表中,我想获得所有表示Hello World的元素索引。 我尝试了以下但它只返回它找到的具有我的搜索条件的第一个索引:
for (int i = 0; i< searchInList.Count; i++) foundHelloWorld[i] = searchInList.IndexOf("Hello World");
有人知道这样做的方法吗?
谢谢
searchInList.Select((value, index) => new {value, index}) .Where(a => string.Equals(a.value, "Hello World")) .Select(a => a.index)
如果您正在尝试搜索的不只是"Hello World"
,那么您可以这样做
searchInList.Select((value, index) => new {value, index}) .Where(a => stringsToSearchFor.Any(s => string.Equals(a.value, s))) .Select(a => a.index)
既然你知道你正在寻找所有的事件,因此你必须遍历整个列表,通过简单地自己检查每个元素,你将获得比使用IndexOf更多的可读性:
var i=0; foreach(var value in searchInList) { if(value == "Hello World") foundHelloWorld.Add(i); //foundHelloWorld must be an IList i++; }
您还可以使用Linq Select方法的重载,该方法在源集合中包含元素的索引; 对于Linq经验丰富的程序员来说,这应该是高度可读的(因此可维护):
foundHelloWorld = searchInList .Select((v,i)=>new {Index = i, Value = v}) .Where(x=>x.Value == "Hello World") .Select(x=>x.Index) .ToList();
上面的代码获取列表并将字符串转换为简单的匿名类型,并将每个项目的位置合并到原始列表中。 然后,它过滤到只匹配的元素,然后它将索引(没有通过过滤更改)投影到新的List对象中。 但是,所有这些转换都会使此解决方案执行速度变慢,因为此语句将多次遍历整个列表。
有点难看但会起作用:
var searchInList = new List(); //Populate your list string stringToLookUp= "Hello world"; var foundHelloWorldIndexes = new List(); for (int i = 0; i < searchInList.Count; i++) if (searchInList[i].Equals(stringToLookUp)) foundHelloWorldIndexes.Add(i);
列表的FindAll方法在这里 。 列表扩展方法在这里 。
这些都可以完全按照您的要求进行操作,并且非常易于使用。 互联网上有很多例子,如果你需要帮助,请告诉我。