2014-10-29 126 views
-2

我需要一个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<string,string>

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

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

我需要此对象传递给一个FormUrlEncodedContent(字典)作为字符串的词典。

我有这样的:

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

而且我想到ComplexDto.ToJson()或ComplexDto对象变换为词典字符串,字符串。

任何想法?

+1

什么是ListIdsDto?也只有一个类,你想用于字典的集合在哪里? – 2014-10-29 10:24:16

+1

什么是应该转换为什么? – 2014-10-29 10:24:20

+0

你究竟希望'ComplexDto'看起来像一个字符串? – 2014-10-29 10:25:16

回答

0

假设你有一个像一些ComplexDto实例的集合:

List<ComplexDto> complexDtoList = ...; 

,你希望有重复键,这将导致异常(否则你也可以使用在首位的字典)。

您可以使用Enumerable.GroupBy来获得唯一的密钥。然后你必须决定你想要做什么1-n Propertie2-每个组的字符串。一种方法是使用String.Join用分隔符Concat的一切:

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

你也可以建立一个Dictionary<string, List<string>>并使用p1Group.Select(dto => dto.Propertie2).ToList()的价值。

相关问题