簡體   English   中英

檢查列表是否<stringcollection>包含列表<string></string></stringcollection>

[英]Check if a list<StringCollection> contains list<string>

給定一個list<StringCollection>如何最有效地檢查所有string是否包含在任何StringCollection中?

例子:

using System;
using System.Collections.Specialized;
using System.Collections.Generic;
                    
public class Program
{
    public static void Main()
    {
        // Create and initializes a new StringCollection.
        StringCollection myCol0 = new StringCollection();
        StringCollection myCol1 = new StringCollection();
        StringCollection myCol2 = new StringCollection();

        StringCollection SearchCol = new StringCollection();

        // Add a range of elements from an array to the end of the StringCollection.
        String[] myArr0 = new String[] { "RED", "car", "boat" };
        myCol0.AddRange( myArr0 );
        
        // Add a range of elements from an array to the end of the StringCollection.
        String[] myArr1 = new String[] { "Blue", "Goku", "Nappa" };
        myCol1.AddRange( myArr1 );
        
        // Add a range of elements from an array to the end of the StringCollection.
        String[] myArr2 = new String[] { "Yellow", "Winter", "Summer" };
        myCol2.AddRange( myArr2 );
        
        // Add a range of elements from an array to the end of the StringCollection.
        String[] myArr3 = new String[] { "Yellow", "Blue", "RED" };
        SearchCol.AddRange( myArr3 );
        
        List<StringCollection> a = new List<StringCollection>();
        a.Add(myCol0);
        a.Add(myCol1);
        a.Add(myCol2);
    }
}

在這種情況下,我想知道SearchCol中的字符串是否包含在List<StringCollection> a中存儲的字符串集合中

在這種情況下,我只想知道哪些 searchCol 字符串不包含在List<StringCollection> a

我看到這一點的唯一方法是通過雙 for 循環? 有沒有比字符串集合更有效的數據結構?

有沒有比字符串集合更有效的數據結構

以什么方式有效? 當然,您通常應該使用IEnumerable<string> (如string[] vor List<string> ),因為StringCollection不是通用的。

但是您也可以使用StringCollection ,您必須將每個項目從 object 轉換為字符串:

var allStrings = a.SelectMany(c => c.Cast<string>());
var searchStrings = SearchCol.Cast<string>();
bool allSearchStringsAreContained = searchStrings.All(allStrings.Contains);

至於“如何最有效地做”,這種簡單的方法是有效的,但是如果您有大量要搜索的字符串或大量字符串列表,則可以使用基於集合的方法:

HashSet<string> set = new HashSet<string>(searchStrings);
bool allSearchStringsAreContained = set.IsSubsetOf(allStrings);

最后,如果您想忽略大小寫,那么將“RED”和“Red”視為相同:

方法一:

bool allSearchStringsAreContained = searchStrings.All(s => allStrings.Contains(s, StringComparer.OrdinalIgnoreCase));

方法二:

HashSet<string> set = new HashSet<string>(searchStrings, StringComparer.OrdinalIgnoreCase);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM