【问题标题】:Is there a way to extract primitive fields from a Dictionary of objects in C#?有没有办法从 C# 中的对象字典中提取原始字段?
【发布时间】:2010-05-06 14:23:09
【问题描述】:

这是我想要做的:

ObjectA
{
    int ID;
    string name;
}

我想将 Dictionary 转换为 List,其中列表中的字符串是字典中 ObjectAs 的 .name 值。显然我可以手动迭代字典值并以这种方式构建列表,但我希望在 C#/.NET 中有更简单或更快的方法。 LINQ 解决方案很好,如果它比/一样快更简单和更快:

List<string> aNames = new List<string>();
foreach(ObjectA a in DictionaryA.Values)
aNames.Add(a.name);

【问题讨论】:

    标签: c# linq dictionary


    【解决方案1】:

    这是马修回答的非查询表达式形式:

    var names = DictionaryA.Values.Select(x => x.name).ToList();
    

    (当我只进行单次选择或单次查询时,我倾向于不使用查询表达式,尤其是当我还需要调用另一个方法时,例如ToList。)

    或者:

    var names = DictionaryA.Select(x => x.Value.name).ToList();
    

    【讨论】:

      【解决方案2】:
      (from val in DictionaryA.Values select val.name).ToList()
      

      【讨论】:

        【解决方案3】:

        一旦您有查询,有很多方法可以做到这一点:

        IQueryable<string> query = DictionaryA.Values.Select(v => v.name);
        
        //use the Constructor of List<T> that accepts IEnumerable<T>
        List<string> aNames = new List<string>(query);
        //
        //or use the AddRange method for existing Lists
        List<string> aNames = new List<string<();
        aNames.AddRange(query);
        //
        //or use the Enumerable.ToList extension method
        List<string> aNames = query.ToList();
        

        【讨论】:

        • 不过,这不是“名称”部分。
        • 再看问题。他不想要字典值的列表。他想要每个字典对象的属性值列表。
        猜你喜欢
        • 2021-05-15
        • 2019-04-04
        • 2020-03-24
        • 2021-09-04
        • 2022-01-14
        • 2016-03-03
        • 1970-01-01
        • 1970-01-01
        • 2019-05-25
        相关资源
        最近更新 更多