从源列表中获取属性并添加到新列表,然后转换为Json

时间:2019-03-13 20:39:45

标签: c#

给出:

List<AddressData> sourceList = new List<AddressData>();

我需要在sourceList(FullAddress)中获取一个属性,并使其成为一个Json字符串数组

class AddressData
{
  public string Street {get; set;}
  public string City {get; set;}
  public string State {get; set;}
  public string Zip {get; set;}
  public string FullAddress { get { return Street + "," + City "," + "State" + "," + Zip } }
}

我的思考过程:
1.创建一个名为有效负载的新List()
2.遍历该列表,并将FullAddress添加到有效负载列表中
3.序列化有效负载列表

询问:是否有更简洁的方法?

有效载荷样本:

[
  { 'address': 'value1'},
  { 'address': 'value2'},
]  

1 个答案:

答案 0 :(得分:1)

如果您还不了解Linq,那么Select扩展程序就可以做到。

我在这里创建了一个演示: https://dotnetfiddle.net/FMZK50

set.seed(1)
testsamples=sample(1:nrow(alcohol), size=.10*nrow(alcohol))
test=alcohol[testsamples,]
train=alcohol[-testsamples,]
nrow(test)

使用Newtonsoft.Json,序列化非常简单:

public static List<CondensedData> GetAddresses(List<AddressData> data)
{
    return data.Select(m=>new CondensedData(){Address=m.FullAddress}).ToList();
}
public class CondensedData
{
    public string Address {get;set;}
}