[英]Format string for a TimeSpan that adds the days to the string only if they are non-zero
[英]Join non-zero length variables into a string
我通过将长字符串解析为几个变量:
Year
Make
Model
Color
ColorLower
Style
根据记录,我可能会在一些或所有这些变量中有详细信息。 但是,在大多数情况下,有些是空白的。 在填充变量之后,将它们添加到数据库字段中,该字段是汽车/车辆的描述。
目前,我的if / else块是一对一的,如果变量的长度为非零,则串联的描述变量
if (length($Year)>0)
{
$Description == $Description + " " + Year
}
elsif (length($Make) > 0)
$Description == $Description + " " + $Make
} ...and so on
现在我正在工作,我想听听是否有一种更短,更紧凑的方法可以最大化我的代码。
谢谢!
更好的方法是使用StringBuilder
using System;
using System.Text;
namespace stringy
{
class MainClass
{
public static void Main (string[] args)
{
string hello = "Hello World!";
int i = 123;
double d = 3.14;
StringBuilder sb = new StringBuilder();
sb.Append(hello);
sb.Append(i);
sb.Append(d);
Console.WriteLine (sb.ToString());
}
}
}
添加字符串包括大量分配和重新分配。
string Year = "2015", Make = "Ford", Model = "Rustbucket",
Color = "Red", ColorLower = "Green", Style = "Car";
string[] stuff = { Year, Make, Model, Color, ColorLower, Style };
string Description = "Start ";
Description+=String.Join(" ", stuff.Where(t => t != ""));
不痛! 没有收获! 检查和内存优化:
public class Entity{
public string Year {get;set;}
public string Make {get;set;}
public string Model {get;set;}
public string Color {get;set;}
public string ColorLower {get;set;}
public string Style {get;set;}
public string Description{
get {
string format = "{0} ";
StringBuilder sb = new StringBuilder();
sb.Append(!string.IsNullOrEmpty(Year) && !string.IsNullOrEmpty(Year.Trim())
? string.Format(format, Year.Trim()) : string.Empty);
sb.Append(!string.IsNullOrEmpty(Make) && !string.IsNullOrEmpty(Make.Trim())
? string.Format(format, Make.Trim()) : string.Empty);
sb.Append(!string.IsNullOrEmpty(Model) && !string.IsNullOrEmpty(Model.Trim())
? string.Format(format, Model.Trim()) : string.Empty);
sb.Append(!string.IsNullOrEmpty(Color) && !string.IsNullOrEmpty(Color.Trim())
? string.Format(format, Color.Trim()) : string.Empty);
sb.Append(!string.IsNullOrEmpty(ColorLower) && !string.IsNullOrEmpty(ColorLower.Trim())
? string.Format(format, ColorLower.Trim()) : string.Empty);
sb.Append(!string.IsNullOrEmpty(Style) && !string.IsNullOrEmpty(Style.Trim())
? string.Format(format.Trim(), Style.Trim()) : string.Empty);
return sb.ToString();
}
}
}
static void Main()
{
var e1 = new Entity{Year="Y",Make="M",Model="Md",
Color="C",ColorLower="CL",Style="S"};
Console.WriteLine(e1.Description); // 'Y M Md C CL S'
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.