【问题标题】:Trying to extract a list of keys from a .NET Dictionary尝试从 .NET 字典中提取键列表
【发布时间】:2011-07-11 06:21:30
【问题描述】:

怀疑我的大脑今天不工作 - 我需要提取一个键列表等:

Dictionary<string, MyClass>  myDict;
List<String> myKeys = myDict.Keys;

第二行编译失败,因为 Keys 属性返回“KeyCollection”类而不是键对象列表。

【问题讨论】:

标签: c# .net dictionary


【解决方案1】:

使用 LINQ,您可以执行以下操作...

List<String> myKeys = myDict.Keys.ToList();

但是,根据您对键的目标(选择性枚举等),使用键集合而不是转换为列表可能更有意义。

【讨论】:

  • 谢谢 - 太棒了:我需要掌握 Linq 的窍门!
  • 啊,所以我缺少的只是using System.Linq; 我从来没有习惯所有这些突然出现的扩展方法......
【解决方案2】:

是的,你可以试试 - IEnumerable&lt;String&gt; myKeys = myDict.Keys;

使用IEnumerable(更通用的类型)总是一个好主意。

【讨论】:

    【解决方案3】:

    如果你需要一份真实的清单:

    List<string> myKeys = new List<string>(myDict.Keys);
    

    【讨论】:

      【解决方案4】:

      KeyCollection 实现了IEnumerable 接口。

      您可以使用扩展方法将其转换为列表。

      List<String> myKeys = myDict.Keys.ToList();
      

      或者使用不同的构造函数:

      List<String> myKeys = new List<String>(myDict.Keys);
      

      【讨论】:

        【解决方案5】:

        我已经创建了一个简化的字典:

        using System;
        using System.Collections;
        using System.Collections.Generic;
        
        namespace CS_Library
        {
            public sealed class Dict : IEquatable<Dict>, IDict
            {
                private ArrayList keys, values;
        
                private int LocalCount; public int Count { get => LocalCount; }
        
                public Dict()
                {
                    keys = new ArrayList();
                    values = new ArrayList();
                }
        
                public Dict(ArrayList keys, ArrayList values)
                {
                    this.keys = keys;
                    this.values = values;
                }
        
                ~Dict() { }
        
                public object this[object key] { get => values[keys.IndexOf(key)]; }
                public int Add(object key, object value) // The more strange is the Visual Studio don't color the 'value'
                {
        
                    if (keys.IndexOf(key) > -1 || values.IndexOf(value) > -1)
                    {
                        return -1;
                    }
                    LocalCount = keys.Add(key);
                    return values.Add(value);
                }
                public void Override(object newKey, object newValue, object key)
                {
                    if (keys.IndexOf(newKey) > -1 || values.IndexOf(newValue) > -1)
                    {
                        return;
                    }
                    keys[keys.IndexOf(key)] = newKey;
                    values[keys.IndexOf(key)] = newValue;
                }
        
                public void Delete(object key)
                {
                    if (keys.IndexOf(key) == -1)
                    {
                        return;
                    }
                    values.RemoveAt(keys.IndexOf(key));
                    keys.Remove(key);
                }
        
                public void DeleteAt(int index)
                {
                    if (index < 0 || index > keys.Count)
                    {
                        return;
                    }
                    keys.RemoveAt(index);
                    values.RemoveAt(index);
                }
        
                public void Erase()
                {
                    values = null;
                    keys = null;
                }
        
                public void Rebuild(ArrayList newKeys, ArrayList newValues)
                {
                    if (keys != null && values != null)
                    {
                        throw new InvalidOperationException("Expected 'Erase()' method before this one. Or the 'Queue_Rebuild()' method instead this one.");
                    }
                    keys = newKeys;
                    values = newValues;
                }
        
                public void Queue_Rebuild(ArrayList newKeys, ArrayList newValues)
                {
                    Erase();
                    Rebuild(newKeys, newValues);
                }
        
                public override bool Equals(object obj)
                {
                    return Equals(obj as Dict);
                }
        
                public bool Equals(Dict other)
                {
                    return other != null &&
                           EqualityComparer<ArrayList>.Default.Equals(keys, other.keys) &&
                           EqualityComparer<ArrayList>.Default.Equals(values, other.values) &&
                           LocalCount == other.LocalCount;
                }
        
                public override int GetHashCode()
                {
                    return HashCode.Combine(keys, values, LocalCount);
                }
        
                public override string ToString()
                {
                    string r = "{ ";
                    bool first = true;
                    for (int i = 0; i < LocalCount; i++)
                    {
                        if (!first)
                        {
                            r += ", ";
                        }
                        else
                        {
                            first = false;
                        }
                        r += $"{keys[i]}:{values[i]}";
                    }
                    return r + " }";
                }
        
                public static bool operator ==(Dict left, Dict right)
                {
                    return EqualityComparer<Dict>.Default.Equals(left, right);
                }
        
                public static bool operator !=(Dict left, Dict right)
                {
                    return !(left == right);
                }
        
                public static Dict operator +(Dict left, Dict right)
                {
                    Dict r = left;
                    for (int i = 0; i < right.Count; i++)
                    {
                        r.Add(right.keys[i], right.values[i]);
                    }
                    return r;
                }
        
            }
        }
        

        还没有完成,所以你可以做任何改变。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-09-26
          • 1970-01-01
          • 2021-09-17
          • 1970-01-01
          • 1970-01-01
          • 2018-04-03
          • 1970-01-01
          • 2017-12-14
          相关资源
          最近更新 更多