0
votes

I have three sets of listboxes, I move items from lb1 to lb2, from lb3 to lb4 and from lb5 to lb6. The listboxes on the left contains the same items and I don't want the user to be able to submit the page if one or more items from the left listboxes is added to more than one listbox to the right. For example, item A in lb1, lb3 and lb5 can only be saved in either lb2, lb4 or lb6, not in two or three of them.

I want to perform this check before submitting the page (and later on I will add validation with javascript) and I wonder what is the most efficient way to do this.

Add all items to a list and check if there are any duplicates?

Thanks in advance.

Edit: something like this:

            List<string> groupList = new List<string>();
            foreach (ListItem item in lbFullAccess.Items)
            {
                groupList.Add(item.Value.ToString());
            }
            foreach (ListItem item in lbContributor.Items)
            {
                groupList.Add(item.Value.ToString());
            }
            foreach (ListItem item in lblReadOnly.Items)
            {
                groupList.Add(item.Value.ToString());
            }
1
Why just not to iterate over the listboxes and check ? How about using DISTINCT for each list box on submiting ?Ostap

1 Answers

0
votes

Well, there's a hundred different ways you could do it. Absolutely nothing wrong with your suggestion of iteration.

You could have a little fun with LINQ:

public bool AreAllValuesUnique()
{
    // Build up a linq expression of all of the ListItems
    // by concatenating each sequence
    var allItems = lbFullAccess.Items.Cast<ListItem>()
        .Concat(lbContributor.Items.Cast<ListItem>())
        .Concat(lbReadOnly.Items.Cast<ListItem>());

    // Group the previous linq expression by value (so they will be in groups of "A", "B", etc)
    var groupedByValue = allItems.GroupBy(i => i.Value);

    // Finally, return that all groups must have a count of only one element
    // So each value can only appear once
    return groupedByValue.All(g => g.Count() == 1);
}

Not really sure about the performance of calling Cast (converting each element of the ListItemCollection to a ListItem, resulting in an IEnumerable) on each collection, but it is probably negligible.