假设:
我需要分割并创建字符串集合的字符串dayCodes
(即"MWF"
或"MRFU"
),以便我可以得到星期几字符串的列表(即{ {1}}或"Monday", "Wednesday", "Friday"
)。
"Monday", "Thursday", "Friday", "Sunday"
问题:
问题在于你不能将// this causes a run-time exception because you can't cast Char to String
var daysArray = days.ToCharArray().Cast<string>().ToArray();
// for each dayCode, overwrite the code with the day string.
for (var i = 0; i < daysArray.Length; i++)
{
switch (daysArray[i])
{
case "M":
daysArray[i] = "Monday";
break;
case "T":
daysArray[i] = "Tuesday";
break;
case "W":
daysArray[i] = "Wednesday";
break;
case "R":
daysArray[i] = "Thursday";
break;
case "F":
daysArray[i] = "Friday";
break;
case "S":
daysArray[i] = "Saturday";
break;
case "U":
daysArray[i] = "Sunday";
break;
}
}
daysArray[daysArray.Length - 1] = "and " + daysArray[daysArray.Length - 1];
return string.Join(", ", daysArray);
强制转换为Char
,我认为这是有意义的,因为一个不是从另一个继承的。您仍然认为编译器会将String
强制转换为一个字符长Char
。
有没有快速的方法(比如使用String
)这样做,所以我不必从头开始创建Cast<string>()
?
答案 0 :(得分:23)
只需使用char.ToString()
即可:
var daysArray = days.ToCharArray().Select( c => c.ToString()).ToArray();
或者,在我的脑海中有一个更好的解决方案,为什么不直接将字符串与字典一起用于映射:
var daysArray = days.Select( c => dayMapping[c]).ToArray();
dayMapping
只有Dictionary<char, string>
映射到全天名称:
Dictionary<char, string> dayMapping = new Dictionary<char,string>()
{
{ 'M', "Monday" },
{ 'T', "Tuesday" }
//and so on
}
答案 1 :(得分:2)
char[] daysCodeArray = days.ToCharArray();
string[] daysArray = daysCodeArray.Select(el =>
{
switch (el)
{
case 'M':
return "Monday";
case 'T':
return "Tuesday";
case 'W':
return "Wednesday";
case 'R':
return "Thursday";
case 'F':
return "Friday";
case 'S':
return "Saturday";
case 'U':
return "Sunday";
}
throw new ArgumentException("Invalid day code");
}).ToArray();
如果需要,可以将lambda更改为单独的方法。
答案 2 :(得分:1)
你可以这样做:
var dayCode = "MWF";
var daysArray = new List<string>();
var list = new Dictionary<string, string>{
{"M", "Monday"},
{"T", "Tuesday"},
{"W", "Wednesday"},
{"R", "Thursday"},
{"F", "Friday"},
{"S", "Saturday"},
{"U", "Sunday"}
};
for(int i = 0,max = dayCode.Length; i < max; i++)
{
var tmp = dayCode[i].ToString();
if(list.ContainsKey(tmp))
{
daysArray.Add(list[tmp]);
}
}
Console.WriteLine(string.Join(",", daysArray));
输出:
答案 3 :(得分:1)
在标题中回答任何在搜索中发现此问题的人...(不是所描述的问题......这是之前的帖子之一。)
var t =&#34; ABC&#34;;
var s = t.ToCharArray()。选择(c =&gt; c.ToString())。ToArray();