您可以尝试使用Join
方法中的内嵌terniary:
string.Join("-", string.IsNullOrEmpty(e.Company) ? "fired" : e.Company, e.Name)
编辑(我误读 '弗雷德' 拼写错误的解雇)。
正如在另一个答案中提到的,扩展方法将清理代码。你会将难看的代码移动到不同的地方。
作为一个扩展方法的替代方案中,我建议类似的东西允许更多的参数在稍后的时间如下:
public static string ExcludeEmptiesJoin(params string[] args) {
string outValue = string.Empty;
foreach (var arg in args.Where(s => !string.IsNullOrEmpty(s))) {
if (string.IsNullOrEmpty(outValue)) {
outValue = arg;
} else {
outValue = string.Join("-", outValue, arg);
}
}
return outValue;
}
用法:
Console.WriteLine(ExcludeEmptiesJoin("Company", "Fred"));
Console.WriteLine();
Console.WriteLine(ExcludeEmptiesJoin("", "Fred"));
Console.WriteLine();
Console.WriteLine(ExcludeEmptiesJoin("Company", ""));
Console.WriteLine();
Console.WriteLine(ExcludeEmptiesJoin("Company", "", "4/4/1979"));
Console.WriteLine();
Console.WriteLine(ExcludeEmptiesJoin("Company", "Fred", "4/4/1979"));
输出:
Company-Fred
弗雷德
公司
公司-4 /1979分之4
公司弗雷德-4 /1979分之4
他有一个内嵌他的问题是三元的。 –
这看起来像是一个很好的方法,它会测试它,并标记正确,如果它的所有好 –
如果你去这个解决方案,我会建议用'StringBuilder'替换'string.Join'。 – venerik