【问题标题】:Compare Dictionary and List比较字典和列表
【发布时间】:2015-01-11 14:22:06
【问题描述】:

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

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

List<string> elementToRemove.

【问题讨论】:

  • 欢迎来到 SO。请发布您的代码并尝试使用您的代码解释您的问题。否则,我们很难达成共识并提供任何帮助。
  • 请参阅tinyurl.com/stack-checklist 以获取发布时要运行的快速清单。我敢肯定,当我们知道您真正想要什么时,使用 LINQ 这将相当容易......(我们不知道列表将包括什么,或者 cwObject 是什么......)
  • 两者相比如何? intstringstring 中有什么内容?格式是什么?
  • 我想比较 Dic 样式(字符串)中等于列表中项目(字符串到)的值,并创建一个新的 dic,在其中删除等于项目..提前致谢
  • 你能提供一些示例数据吗?

标签: c# dictionary


【解决方案1】:

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

对于本示例,我假设 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);

【讨论】:

    【解决方案2】:

    您的问题不完整,但我尽我所能编写示例,试试这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-21
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多