简体   繁体   中英

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. 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<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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM