比较字典和列表

Compare Dictionary and List

我有一个字典 ==> Dictionary<int, cwObject> 样式,在 cwObject 值中具有不同的 属性,我想将它与 属性 的列表进行比较并创建一个新字典,其中等于列表的值被删除。

Dictionary<int, cwObject> styles = stylesOT.Objects;

List<string> elementToRemove.

你的问题不完整,但我尽力写了这个例子,试试这个:

//example of class cwObject 
 public class cwObject{
    public string stringtocompare;
    public object anyotherobject;


}
//main process
 static void Main(string[] args)
    {
        //List contains string to remove
        List<string> stringtoremove = new List<string>();
        stringtoremove.Add("stringtoremove");

        //dummy data for cwObject
        cwObject cw = new cwObject();
        cw.stringtocompare = "stringok";
        cw.anyotherobject = "anything";

        cwObject cw1 = new cwObject();
        cw1.stringtocompare = "stringtoremove";
        cw.anyotherobject = 100;

        //dummy data for dictionary to compare
        Dictionary<int, cwObject> dictcw = new Dictionary<int, cwObject>();
        dictcw.Add(0,cw);
        dictcw.Add(1,cw1);

        //new dictionary for container of results
        Dictionary<int,cwObject> filtereddict = new Dictionary<int,cwObject>();
        cwObject cwtemp = null;

        //start enumerating
        foreach (string str in stringtoremove)
        {
            foreach (KeyValuePair<int, cwObject> entry in dictcw)
            {
                cwtemp = entry.Value;
                if (!cwtemp.stringtocompare.Equals(str)) {
                    filtereddict.Add(entry.Key,entry.Value);

                }
            }
        }

        //output the result
        foreach (KeyValuePair<int, cwObject> entry in filtereddict)
        {
            cwtemp = entry.Value;
            Console.WriteLine(cwtemp.stringtocompare);
        }

        Console.ReadLine();
    }

您可以从列表中创建一个哈希集以进行快速查找(或从一开始就将其设为哈希集),然后您可以从字典中过滤项目并从中创建一个新字典。

对于此示例,我假设 cwObject 有一个名为 element 的字符串 属性,您将其与列表中的字符串进行比较:

HashSet<string> remove = new HashSet<string>(elementToRemove);

Dictionary<int, cwObject> remaining =
  styles.Where(o => !remove.Contains(o.Value.element))
  .ToDictionary(o => o.Key, o => o.Value);