RESOLVED
Oddly, it appeared that what was happening here, was that the string[] collection was being iterrated through when it had no elements. Because of that, every single item would be removed from the user list. Added an additional check to ensure that nicks.Count !=0, and it adds and works perfectly. Have to love when code does things you do not expect 😉
—[INITIAL ISSUE]—
So, i’m a bit confused here.
When we connect to our server, we are given a string collection result string[]. We then parse that string collection, and add names to a listview. However, we need to also parse the listview, and remove any items which do not appear in the string collection.
I can’t seem to figure out a way to properly do that. I know it’s easy, but I’ve failed so far at anything I’ve tried, which totally isn’t cool 🙁
Code to filter out the string collection to the listview and not add duplicates:
foreach (var nick in nicks)
{
if (string.IsNullOrEmpty(nick)) continue;
var lvi = new ListViewItem
{
Text = nick,
Group = nick.StartsWith("@") ? listViewEx1.Groups[0] : listViewEx1.Groups[1]
};
if (listViewEx1.Items.Count != 0)
{
var foundItem = listViewEx1.FindItemWithText(nick, true, 0, false);
if (foundItem != null) continue;
}
lvi.ImageIndex = 0;
listViewEx1.Items.Add(lvi);
}
So, how can I conversely compare the items in the listview, with the items in the string collection, and remove those that do not exist?
Debug Information
Element in 'nicks': Bot
Element in 'nicks': Test
Element in 'nicks': @Mike
Element in 'nicks': @Jack
Element in 'nicks': Joe
Element in 'nicks': Nancy
Element in 'nicks': Roger
Element in 'nicks':
Does not contain: @Mike
Does not contain: @Jack
Does not contain: Bot
Does not contain: Joe
Does not contain: Test
Does not contain: Nancy
Does not contain: Roger
So oddly, even though the nicks[] collection contains the item, and the item.Text contains the nick, the .Contains() call is not matching it.
If these are just simple strings then something like this should work:
The reason for the separate remove loop is that you don’t want to modify the
Itemscollection during an iteration, otherwise you get an exception.