简体   繁体   English

如何检查一个项目是否存在于多个列表框中? ASP.NET/C#

[英]How to check if an item exists in more than one listbox? ASP.NET/C#

I have three sets of listboxes, I move items from lb1 to lb2, from lb3 to lb4 and from lb5 to lb6. 我有三组列表框,将项目从lb1移至lb2,从lb3移至lb4,从lb5移至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. 例如,lb1,lb3和lb5中的项目A只能保存在lb2,lb4或lb6中,而不能保存在其中的两个或三个中。

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. 我想在提交页面之前执行此检查(稍后我将使用javascript添加验证),我想知道最有效的方法是什么。

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());
            }

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: 您可以在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. 对于每个集合调用Cast的性能(将ListItemCollection的每个元素转换为ListItem,导致IEnumerable)的性能并不确定,但它可以忽略不计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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