[英]Loop through an array of strings and compare to previous values
I need to loop through an array of strings and know if I've seen a particular string value before. 我需要遍历一个字符串数组,并知道我之前是否看过特定的字符串值。 Normally, I would have written something like this in other languages:
通常,我会用其他语言编写如下内容:
String oldValue="";
String newValue;
for (i=0;i<myarray.Length;i++)
{
newValue=myarray[i];
if (oldValue==newValue)
break;
...
oldValue=newValue;
}
However, this doesn't work in C# as Strings are immutable. 但是,这在C#中不起作用,因为字符串是不可变的。 It looks like I could do this with a Regular Expression if I just replaced the entire string, but that seems like extra overhead.
如果我只是替换了整个字符串,则看起来可以使用正则表达式来执行此操作,但这似乎是额外的开销。 How have other people handled this before?
其他人以前如何处理?
Thank you 谢谢
I'm not sure whether I understood your question, but if what you intend is to detect the first string that is repeated in the array, you need to remember all of them. 我不确定我是否理解您的问题,但是如果您打算检测数组中重复的第一个字符串,则需要记住所有这些字符串。 I suggest using a HashSet, so at least it runs in O(n), like this:
我建议使用HashSet,因此至少它可以在O(n)中运行,如下所示:
HashSet<string> prevSet = new HashSet<string>();
foreach ( string str in myArray )
if ( !prevSet.Add(str) ) return str;
You could do this to make a list of word frequencies: 您可以这样做以列出单词频率:
var frequency =
myarray
.GroupBy(x => x)
.Select(x => new
{
Value = x.Key,
Count = x.Count(),
});
You could then just filter this list where Count > 1
. 然后,您可以只在
Count > 1
过滤此列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.