转换列表中的项目<>连接和格式化的字符串?

时间:2010-07-16 22:10:47

标签: c# .net

鉴于:

    protected class Marker { 
        public string Name { get; set; }
        public string Lat { get; set; }
        public string Long { get; set; } 
    };

List<Marker> allMarkers = new List<Marker>();
allMarkers.Add(new Marker{Name="Bondi Beach", Lat = "-33.890542", Long = "151.274856"});
allMarkers.Add(new Marker{Name="Coogee Beach", Lat = "-33.923036", Long = "151.259052"});
allMarkers.Add(new Marker{Name="Cronulla Beach", Lat = "-34.028249", Long = "151.157507"});
allMarkers.Add(new Marker{Name="Manly Beach", Lat = "-33.800101", Long = "151.287478"});
allMarkers.Add(new Marker{Name="Maroubra Beach", Lat = "-33.950198", Long = "151.259302"});

我想转换为这种格式的字符串:

['Bondi Beach', -33.890542, 151.274856],
['Coogee Beach', -33.923036, 151.259052],
['Cronulla Beach', -34.028249, 151.157507],
['Manly Beach', -33.800101, 151.287478],
['Maroubra Beach', -33.950198, 151.259302]

是否有一种单行方式来执行此操作,类似于string.Join(),或者我是否必须通过List上的foreach手动执行并使用stringbuilder.appendformat()?

3 个答案:

答案 0 :(得分:7)

如果Marker是您自己的类,请考虑覆盖ToString()方法以按照您的方式显示每一行。然后,您可以使用简单的String.Join()将它们组合在一起。

protected class Marker
{
    public string Name { get; set; }
    public string Lat { get; set; }
    public string Long { get; set; }
    public override string ToString()
    {
        return String.Format("['{0}', {1}, {2}]", Name, Lat, Long);
    }
};

然后,使用:

List<Marker> allMarkers = new List<Marker>();
allMarkers.Add(new Marker { Name = "Bondi Beach", Lat = "-33.890542", Long = "151.274856" });
allMarkers.Add(new Marker { Name = "Coogee Beach", Lat = "-33.923036", Long = "151.259052" });
allMarkers.Add(new Marker { Name = "Cronulla Beach", Lat = "-34.028249", Long = "151.157507" });
allMarkers.Add(new Marker { Name = "Manly Beach", Lat = "-33.800101", Long = "151.287478" });
allMarkers.Add(new Marker { Name = "Maroubra Beach", Lat = "-33.950198", Long = "151.259302" });
Console.Write(String.Join(",\n", allMarkers));

注意:如果您正在处理大量标记并注意到性能不佳,请考虑将String.Format()行重写为:

return "['" + Name + "', " + Lat.ToString() + ", " + Long.ToString() + "]";

根据您的使用情况,您可能会注意到这种情况会更好(或更糟)。

答案 1 :(得分:4)

你可以使用String.Join和一个简单的LINQ Select将它们投射到你想要的格式......

   allMarkers.Select(m => "['" + m.Name + "', " + m.Lat + ", " + m.Long + "]")

但是您可能希望考虑使用DataContract序列化将数据序列化为JSON,而不是发明自己的序列化对象表示法。

答案 2 :(得分:0)

通过使用扩展方法,您可以执行类似这样的操作

static class Extensions
{
   static string ToStringAll(this List<Marker> markers)
   {
      string all = "";

      foreach (var marker in markers)
      {
         all += marker.ToString() + ",";
      }

      return all.Trim(',');
   }
}

然后您将来需要使用的是

allMarkers.ToStringAll();