简体   繁体   English

将Address对象转换为String的最佳方法是什么?

[英]What is the best way to convert an Address object to a String?

I have an Address object that has properties AddressLine1, AddressLine2, Suburb, State, ZipCode. 我有一个地址对象,该对象具有属性AddressLine1,AddressLine2,Suburb,State,ZipCode。 (there are more but this is enough for the example). (还有更多,但是对于示例来说,这已经足够了)。 Also, each of these properties are strings. 同样,这些属性都是字符串。 And I'm using C# 3.0. 我正在使用C#3.0。

I'm wanting to represent it as a string but as I'm doing that I'm finding that I'm creating a method with a high cyclomatic complexity due to all the if-statements... 我想将其表示为字符串,但是当我这样做时,由于所有的if语句,我发现我正在创建一种具有高圈复杂度的方法...

Assuming the string assigned to each property is the same as the name of the property (ie AddressLine1 = "AddressLine1")...I want the address to be represented as follows: 假设分配给每个属性的字符串与属性的名称相同(即AddressLine1 =“ AddressLine1”)...我希望该地址表示如下:

"AddressLine1 AddressLine2 Suburb State ZipCode". “ AddressLine1 AddressLine2郊区状态邮政编码”。

Now, the original way I had done this was by a simple String.Format() 现在,我执行此操作的原始方法是通过一个简单的String.Format()

String.Format("{0} {1} {2} {3} {4}", address.AddressLine1, 
address.AddressLine2, address.Suburb, address.State, address.ZipCode);

This is all well and good until I've found that some of these fields can be empty...in particular AddressLine2. 一切都很好,直到我发现其中一些字段可以为空...特别是AddressLine2。 The result is additional unneeded spaces...which are particularly annoying when you get several in a row. 结果是增加了不必要的空间...当连续放置多个空间时,这尤其令人讨厌。

To get around this issue, and the only solution I can think of, I've had to build the string manually and only add the address properties to the string if they are not null or empty. 为了解决这个问题,这是我能想到的唯一解决方案,我不得不手动构建字符串,并且仅在地址属性不为null或为空时才将其添加到字符串中。

ie

string addressAsString = String.Empty;

if (!String.IsNullOrEmpty(address.AddressLine1))
{
    addressAsString += String.Format("{0}", address.AddressLine1);
}

if(!String.IsNullOrEmpty(address.AddressLine2))
{
    addressAsString += String.Format(" {0}", address.AddressLine2);
}

etc....

Is there a more elegant and/or concise way to achieve this that I'm not thinking about? 是否有更优雅和/或更简洁的方式来实现我所没有考虑的目标? My solution just feels messy and bloated...but I can't think of a better way to do it... 我的解决方案感到混乱且肿胀...但是我想不出更好的方法...

For all I know, this is my only option given what I want to do...but I just thought I'd throw this out there to see if someone with more experience than me knows of a better way. 就我所知,鉴于我想做的事情,这是我唯一的选择...但是我只是想把它扔在那里,看看是否有比我经验更多的人知道更好的方法。 If theres no better option then oh well...but if there is, then I'll get to learn something I didn't know before. 如果没有更好的选择,那就好...但是如果有,那么我将学习以前不知道的东西。

Thanks in advance! 提前致谢!

This possibly isn't the most efficient way, but it is concise. 这可能不是最有效的方法,但是很简洁。 You could put the items you want into an array and filter out the ones without a significant value, then join them. 您可以将所需的项目放入数组中,并过滤掉没有明显价值的项目,然后将它们加入。

var items = new[] { line1, line2, suburb, state, ... };
var values = items.Where(s => !string.IsNullOrEmpty(s));
var addr = string.Join(" ", values.ToArray());

Probably more efficient, but somewhat harder to read, would be to aggregate the values into a StringBuilder , eg 可能更有效,但更难阅读的是将值聚合到StringBuilder ,例如

var items = new[] { line1, line2, suburb, state, ... };
var values = items.Where(s => !string.IsNullOrEmpty(s));
var builder = new StringBuilder(128);
values.Aggregate(builder, (b, s) => b.Append(s).Append(" "));
var addr = builder.ToString(0, builder.Length - 1);

I'd probably lean towards something like the first implementation as it's much simpler and more maintainable code, and then if the performance is a problem consider something more like the second one (if it does turn out to be faster...). 我可能倾向于第一个实现之类的东西,因为它更简单,更易于维护,然后,如果性能存在问题,请考虑更类似于第二个实现(如果确实更快)。

(Note this requires C# 3.0, but you don't mention your language version, so I'm assuming this is OK). (请注意,这需要C#3.0,但是您没有提及您的语言版本,因此我认为这是可以的)。

When putting strings together I recommend you use the StringBuilder class. 将字符串放在一起时,建议您使用StringBuilder类。 Reason for this is that a System.String is immutable, so every change you make to a string simply returns a new string. 原因是System.String是不可变的,因此您对字符串所做的每一次更改都只会返回一个新字符串。

If you want to represent an object in text, it might be a good idea to override the ToString() method and put your implementation in there. 如果要用文本表示对象,则最好重写ToString()方法并将实现放在其中。

Last but not least, with Linq in C# 3.5 you can join those together like Greg Beech just did here, but instead of using string.Join() use: 最后但并非最不重要的一点是,在C#3.5中使用Linq,您可以像Greg Beech一样将它们连接在一起,但是不必使用string.Join(),请使用:

StringBuilder sb = new StringBuilder();
foreach (var item in values) {
  sb.Append(item);
  sb.Append(" ");
}

Hope this helps. 希望这可以帮助。

I would recommend overriding the ToString method, and take an IFormatProvider implementation that defines your custom types. 我建议重写ToString方法,并采用定义您的自定义类型的IFormatProvider实现。

See MSDN at http://msdn.microsoft.com/en-us/library/system.iformatprovider.aspx for information on implementing IFormatProvider. 有关实现IFormatProvider的信息,请参见http://msdn.microsoft.com/zh-cn/library/system.iformatprovider.aspx上的MSDN。

You could then code such as this: 然后可以这样编写:
address.ToString("s"); address.ToString(“ s”); // short address //短地址
address.ToString("whatever"); address.ToString(“随便”); // whatever custom format you define. //您定义的任何自定义格式。

Definitely not the easiest way to do it, but the cleanest IMHO. 绝对不是最简单的方法,而是最干净的恕我直言。 An example of such implementation is the DateTime class. DateTime类是此类实现的一个示例。

Cheers 干杯
Ash

I know this is really old, but I sensed a general solution and implemented mine this way: 我知道这确实很老,但是我感觉到了一个通用的解决方案并以这种方式实现了我的方法:

private static string GetFormattedAddress(
    string address1,
    string address2,
    string city,
    string state,
    string zip)
{
    var addressItems =
        new []
        {
            new[] { address1, "\n" },
            new[] { address2, "\n" },
            new[] { city, ", " },
            new[] { state, " " },
            new[] { zip, null }
        };

    string suffix = null;
    var sb = new StringBuilder(128);

    foreach (var item in addressItems)
    {
        if (!string.IsNullOrWhiteSpace(item[0]))
        {
            // Append the last item's suffix
            sb.Append(suffix);

            // Append the address component
            sb.Append(item[0]);

            // Cache the suffix
            suffix = item[1];
        }
    }

    return sb.ToString();
}

First, an address requires certain information, so you should not allow an address that does not have, say, a zip-code. 首先,地址需要某些信息,因此您不应该允许没有邮政编码的地址。 You can also make sure that they are never null by initialize each property to an empty string, or by requiring each property as arguments to the constructor. 您还可以通过将每个属性初始化为空字符串或要求每个属性作为构造函数的参数来确保它们永远不会为null。 This way you know that you are dealing with valid data already, so you can just output a formatted string with no need for the IsNullOrEmpty checks. 这样,您就知道已经在处理有效数据,因此您只需输出格式化的字符串即可,而无需进行IsNullOrEmpty检查。

I had a similar issue building a multi-line contact summary that could have potentially had several empty fields. 我在构建多行联系摘要时遇到了类似的问题,该摘要可能包含多个空白字段。 I pretty much did the same thing you did, except I used a string builder as to not keep concatenating to a string over and over. 我几乎做了与您相同的事情,除了我使用了字符串生成器以免不断重复连接到字符串。

If your data isn't completely reliable, you'll need to have that logic somewhere - I'd suggest that you create another read-only property (call it something like FormattedAddress) that does that logic for you. 如果您的数据不完全可靠,则需要在某个地方使用该逻辑-我建议您创建另一个只读属性(将其称为FormattedAddress之类的东西)为您执行该逻辑。 That way, you don't have to change any of the code it, at some point, you clean up or otherwise change the rules. 这样,您不必更改任何代码,在某些时候,您可以清理或更改规则。

And +1 for the suggestion to use a stringbuilder, as opposed to concatenating strings. 和+1表示建议使用stringbuilder,而不是连接字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将Object []转换为String []或List的最佳方法<String> - Best way to convert Object[] to String[] or List<String> 将此字符串转换为分钟数的最佳方法是什么? - What is the best way to convert this string into number of minutes? 将返回字符分隔的字符串转换为List <string>的最佳方法是什么? - What is the best way to convert a string separated by return chars into a List<string>? 显示存储在Enumerable中的字符串项目的最佳方法是什么 <string> 宾语? - What is the best way to display string items stored in Enumerable<string> object? 转换字典的最简单方法是什么? <string, string> 到字典 <string, object> ? - What is the leanest way to convert a Dictionary<string, string> to a Dictionary<string, object>? 转换IDictionary的优雅方式是什么? <string, object> 到IDictionary <string, string> - What is an elegant way to convert IDictionary<string, object> to IDictionary<string, string> 转换VB if语句将字符串返回到C#的最佳方法是什么 - What is the best way to convert VB if statement that return a string to C# 转换列表的最佳方法是什么<string>列出<type>在 C# 中 - What is the best way to convert List <string> to List<type> in C# 将枚举转换为字符串的最佳实践方法是什么? - What's the best practice way to convert enum to string? 在Unity(C#)中将UI文本转换为字符串的最佳方法是什么? - What is the best way to convert a UI text to string in Unity (C#)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM