在C#中获取列表中重复项的索引 [英] Getting index of duplicate items in a list in c#
本文介绍了在C#中获取列表中重复项的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种从列表中的关键字搜索中获取列表中所有元素的索引的方法.例如,我的清单有:
I am looking for a way to get the index of all elements in a list from a keyword search within the list. So for example my list has:
Hello World
Programming Rocks
Hello
Hello World
I love C#
Hello
现在从这个字符串列表中,我想获取所有表示Hello World的元素的索引.我尝试了以下操作,但它仅返回找到的具有我的搜索条件的第一个索引:
Now from this list of strings, i want to get all the indices of elements that say Hello World. I have tried the following but it only returns the first index it finds that has my search criteria:
for (int i = 0; i< searchInList.Count; i++)
foundHelloWorld[i] = searchInList.IndexOf("Hello World");
有人知道这样做的方法吗?
Anyone know of a way to do this?
谢谢
推荐答案
searchInList.Select((value, index) => new {value, index})
.Where(a => string.Equals(a.value, "Hello World"))
.Select(a => a.index)
如果您要搜索的内容不只是"Hello World"
,则可以
If you're trying to search for more than just "Hello World"
, you could do
searchInList.Select((value, index) => new {value, index})
.Where(a => stringsToSearchFor.Any(s => string.Equals(a.value, s)))
.Select(a => a.index)
这篇关于在C#中获取列表中重复项的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文