C# 使用Linq Aggregate進行字串陣列串接
今天來了一個需求,大致上的描述為,給我一串用「-」號分割的資料,並且按照以下邏輯實作
- 當分割的陣列長度大於3時,去除陣列[0]與[2]後剩下的字串再用「-」號串接起來
- 陣列長度為2時,去除陣列[0],使用陣列[1]當結果
- 當陣列長度為1時,直接將陣列[0]當結果
原本想用Switch實作,但是念頭一轉,就變成以下代碼了。
static void Main(string[] args)
{
string isStr = "AA-BB-CC";
string[] splitArr = isStr.Split('-');
string result = splitArr.Count() == 1 ?
isStr
: (splitArr.Count() == 2 ?
splitArr[1]
: (splitArr.Count() > 2 ?
splitDeptArr.Where((item, num) => num != 0 && num != 2).Aggregate((current, next) => current + "-" + next)
: splitDeptArr.Where((item, num) => num != 0 && num != 2).Aggregate((current, next) => current + "-" + next)
)
);
Console.WriteLine($"{resultDept}");
Console.ReadKey();
}
不過後來仔細思考了一下,發現上面的方法使用上會有效能問題,每次判斷都要進行一次Count函式調用,所以使用下圖方法。
static void Main(string[] args)
{
string isStr = "AA-BB-CC";
string[] splitArr = isStr.Split('-');
string result = string.Empty;
switch (splitArr.Count())
{
case 1:
result = isStr;
break;
case 2:
result = splitArr[1];
break;
default:
result = splitDeptArr.Where((item, num) => num != 0 && num != 2).Aggregate((current, next) => current + "-" + next);
break;
}
Console.WriteLine($"{result}");
Console.ReadKey();
}