【问题标题】:how to get all of string values from dictionary and object in C#如何从 C# 中的字典和对象中获取所有字符串值
【发布时间】:2016-08-06 17:30:35
【问题描述】:

如何从这个Dictionary 获取所有string

class MyObject
{
public string MyString { get; set; }
public int MyInteger { get; set; }
}
    Dictionary<int, MyObject> dictionary = new Dictionary<int, MyObject>();

如何将所有 Mystring 放入 string[] 中? 谢谢

【问题讨论】:

    标签: c# string visual-studio object dictionary


    【解决方案1】:

    你可以用这个:

    string[] result = dictionary.Values.Select(x=> x.MyString).ToArray();
    

    一个 Dictionary 对象有 2 个属性:KeysValues。您可以随时使用它们。

    • Values 包含字典中所有值的集合。
    • Select 用作投影以仅获取MyObject 中的MyString 属性。
    • ToArray 扩展方法将结果转换为数组,作为您问题中的预期结果。

    【讨论】:

    • 感谢回答,它不起作用。它的 get 对象,但我想要类似 dictionary.values.mystring 的东西
    • @hadi.k 这个答案正是你想要的。
    • Dictionary.Values 是您字典中所有MyObject 的列表。 .Select(x =&gt; x.MyString) 仅抓取您要查找的项目,.ToArray() 将其转换为数组。
    【解决方案2】:
     string[] allStrings = dictionary.Values.ToArray();
    

    【讨论】:

      猜你喜欢
      • 2016-10-24
      • 2016-12-16
      • 1970-01-01
      • 2013-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      相关资源
      最近更新 更多