StringBuilder sb = new StringBuilder();
for (int i = 0; i < daysOfWeek.Length; i++)
{
sb.Append(daysOfWeek[i]);
if (i < daysOfWeek.Length - 2)
sb.Append(", ");
else if (i == daysOfWeek.Length - 2)
sb.Append(" and ");
}
Console.WriteLine(sb.ToString());
我理解这段代码中的所有内容,除了daysOfWeek.Length
从中减去2是什么?
答案 0 :(得分:1)
然而,如果我不得不猜测,那么daysOfWeek
阵列中的i
很多天应该是Sun Mon Tue Wed等。 -2从该数字中减去,然后与7 - 2
所在的迭代进行比较。我对C#不是很熟悉,但是如果数组一周有7天,它应该是0
。由于Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday
是数组中的第一个位置,这意味着它应该打印类似SELECT ActivationTime, COUNT(DISTINCT NodeID) NumberOfID
FROM
CASCADING
GROUP BY ActivationTime
答案 1 :(得分:0)
void Main()
{
var daysOfWeek = GetDaysOfWeek();
MethodA(daysOfWeek);
MethodB(daysOfWeek);
}
void MethodA(string[] daysOfWeek)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < daysOfWeek.Length; i++)
{
sb.Append(daysOfWeek[i]);
if (i < daysOfWeek.Length - 2)
sb.Append(", ");
else if (i == daysOfWeek.Length - 2)
sb.Append(" and ");
}
Console.WriteLine(sb.ToString());
}
void MethodB(string[] daysOfWeek)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < daysOfWeek.Length; i++)
{
sb.Append(daysOfWeek[i]);
if (i < daysOfWeek.Length)
sb.Append(", ");
}
Console.WriteLine(sb.ToString());
}
public string[] GetDaysOfWeek()
{
return (new List<string>{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}).ToArray() ;
}
美化。它坚持&#34;和&#34;在一周的最后一天之前进入字符串构建器。
方法A:星期日,星期一,星期二,星期三,星期四,星期五和星期六
<方法B:周日,周一,周二,周三,周四,周五,周六,
下次你对这样的简单代码有疑问时,试试吧!看看它做了什么。创建一个类似我上面创建的小程序,并在Visual Studio或Linqpad中运行它。
答案 2 :(得分:0)
int i
是用于迭代daysOfWeek
在C#中,数组基于零,这意味着数组的第一个元素是MyArray[0]
MyArray.Length
返回数组中元素的数量,从一开始。
如果您的数组只有1个元素,则.Length
为1;你不能做MyArray[MyArray.Length]
因为那会引起异常;你做MyArray[MyArray.Length - 1]
所以你对你的长度“零基础”。
这是你的评论圈:
for (int i = 0; i < daysOfWeek.Length; i++)
{
sb.Append(daysOfWeek[i]);
if (i < daysOfWeek.Length - 2) //If the element is not the last or the penultimate do something
sb.Append(", ");
else if (i == daysOfWeek.Length - 2) //if the element is the penultimate of my array, instead of a "comma", put an "and".
sb.Append(" and ");
}