我有3个布尔值:
bool Boat, Plane, Car;
还有3个字符串:
string ReloadBoat, ReloadPlane, ReloadCar;
根据这些布尔值(如果为false),我需要在字符串之间添加逗号,并在最后两个字符串之间添加单词“ and”。
string errorMessage = (Boat ? "" : " " + ReloadBoat + ", ") + (Plane ? "" : " " + ReloadPlane + ", ") + (Car ? "" : " " + ReloadCar);
errorMessage = errorMessage.TrimEnd(new[] { ' ', ',' });
对于上述情况,我遇到的问题是,如果Boat和Plane均为假,则我收到的错误消息为“ ReloadBoat,ReloadPlane”。
我希望它是“ ReloadBoat和ReloadPlane”。
如果所有3个布尔值均为false,则errorMessage应该为: ReloadBoat,ReloadPlane和ReloadCar。
答案 0 :(得分:1)
您可以使用此解决方案(代码中的注释):
char comma = ',';
string errorMessage = (Boat ? "" : " " + ReloadBoat + comma) + (Plane ? "" : " " + ReloadPlane + comma) + (Car ? "" : " " + ReloadCar + comma);
// at first trim last comma
errorMessage = errorMessage.TrimEnd(comma);
// then replace the last separating comma with 'and'
int place = errorMessage .LastIndexOf(comma);
// only if comma is found
if(place >= 0)
errorMessage = errorMessage.Remove(place, 1).Insert(place, " and");
答案 1 :(得分:1)
using System;
using System.Linq;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
bool Boat = false, Plane = false, Car = true;
string ReloadBoat = "ReloadBoat", ReloadPlane = "ReloadPlane", ReloadCar = "ReloadCar";
var @string = new[] { ReloadBoat, ReloadPlane, ReloadCar };
var @bool = new[] { Boat, Plane, Car };
var zip = @bool.Zip(@string, (Bool, String) => new { Bool, String })
.Where(i => !i.Bool)
.ToArray();
var lastIndex = zip.Length - 1;
var delimeters = zip.Select((item, index) => index != lastIndex ? ", " : " and ")
.Skip(1)
.Append(string.Empty);
var parts = zip.Zip(delimeters, (z, d) => string.Concat(z.String, d));
var errorMessage = string.Concat(parts);
Console.WriteLine(errorMessage);
}
}
}
输出:
ReloadBoat and ReloadPlane
答案 2 :(得分:1)
您可以有条件地填充列表,然后使用一行来创建消息,以这种方式允许添加其他项。
// start with a list
var errItems = new List<string>();
if (boat) errItems.Add(reloadBoat);
if (plane) errItems.Add(reloadPlane);
if (car) errItems.Add(reloadCar);
// make the error message
var errMsg =
errItems.Count > 1 ?
$"{string.Join(", ", errItems.ToArray(), 0, errItems.Count - 1)} and {errItems[errItems.Count - 1]}" :
errItems.Count > 0 ? errItems[0] : "";
答案 3 :(得分:1)
您可以创建一个列表来保存所有错误字符串。
List<string> msgs = new List<string>();
if(!Boat)
msgs.Add(ReloadBoat);
if(!Plane)
msgs.Add(ReloadPlane);
if(!Car)
msgs.Add(ReloadCar);
通过字符串计数构建消息。
switch(msgs.Count)
{
case 0: return string.Empty;
case 1: return msgs[0];
case 2: return msgs[0] + " and " + msgs[1];
default:
string last = msgs[msgs.Count - 1];
msgs.RemoveAt(msg.Count - 1);
return string.Join(", ", msgs) + " and " + last;
}