【问题标题】:Converting complex object to dictionary<string,string>将复杂对象转换为字典<string,string>
【发布时间】:2014-10-29 10:23:28
【问题描述】:

我需要像这样转换一个 dto 对象类:

 public class ComplexDto 
    {
        public ComplexDto()
        {
            ListIds = new List<ListIdsDto>();            
        }

        public string Propertie1 { get; set; }
        public string Propertie2 { get; set; }

        public IList<int> ListIds { get; set; }        
    }    

dictionary&lt;string,string&gt;

这只是一些类的例子,这个类将被用作这样的json对象:

     {"Propertie1":"ss","Propertie2":"","ListIds":[1,2,3]}

我需要将此对象作为字符串字典传递给 FormUrlEncodedContent(dictionary)。

我有这个:

     var data = new Dictionary<string, string>();            
     data[string.Empty] = ComplexDto.ToJson();      

我想将 ComplexDto.ToJson() 或 ComplexDto 对象转换为 Dictionary 字符串 string。

有什么想法吗?

【问题讨论】:

  • 什么是 ListIdsDto?也只有一个类,要用于字典的集合在哪里?
  • 什么应该被转换成什么?
  • 您希望ComplexDto 看起来是一个字符串吗?
  • 您是否需要能够将字符串表示形式转换回 ComplexDto 实例?
  • 我误读了您的问题,我猜您想将 dto 的属性作为 property.name property.value 的字典返回

标签: c# dictionary


【解决方案1】:

假设您有一个包含一些 ComplexDto 实例的集合,例如:

List<ComplexDto> complexDtoList = ...;

并且您希望存在会导致异常的重复键(否则您可能首先使用字典)。

您可以使用Enumerable.GroupBy 获取唯一键。然后你必须决定你想用每个组的 1-n Propertie2-strings 做什么。一种方法是使用String.Join 用分隔符连接所有内容:

Dictionary<string, string> result = complexDtoList
    .GroupBy(dto => dto.Propertie1)
    .ToDictionary(
        p1Group => p1Group.Key,
        p1Group => string.Join(",", p1Group.Select(dto => dto.Propertie2)));

您还可以构建一个Dictionary&lt;string, List&lt;string&gt;&gt; 并使用p1Group.Select(dto =&gt; dto.Propertie2).ToList() 作为值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-29
    • 2021-11-17
    • 1970-01-01
    • 2015-01-13
    • 2011-02-07
    相关资源
    最近更新 更多