本文介绍了如果循环变量的值是模式LetterNumberNumber的字符串,则为For循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当循环变量是整数时,我知道可以用于循环.我强烈需要制作一个for循环,其中循环变量将采用值A00,A01,...,A99,B00,B01,B99,...,Z99.是否允许在C#中使用混合模式作为循环变量的值?

I know to use for loops when loop variable is integer. I strongly needed to make a for loop where loop variable will take the values A00, A01, ..., A99, B00, B01, B99, ..., Z99. Are we allowed to use mixed patterns as the values of loop variables in C#?

在这种情况下如何增加循环变量?我想做的事情的草稿:
for(字符串i = A00,A01,...,Z99; ???; ???)
{...}

How can we increment the loop variable in such a situation? Draft of what I wanted to do:
for (string i = A00, A01, ...,Z99; ???; ???)
{...}

如果不允许我们将这些值用作循环变量,该怎么办才能解决这种情况?

If we are not allowed to use such values as the loop variable, what can be done to handle the situation?

有什么想法吗?

推荐答案

和不可避免的LINQ变体-您可以使用LINQ和Enumerable.Range生成字母和数字序列,例如:

And the inevitable LINQ variant - you can generate a sequence of letters and numbers using LINQ and Enumerable.Range, eg:

var maxLetters=3;
var maxNumbers=3;

var values=from char c in Enumerable.Range('A',maxLetters).Select(c=>(char)c)
           from int i in Enumerable.Range(1,maxNumbers)
           select String.Format("{0}{1:d2}",(char)c,i);

foreach(var value in values)
{
    Console.WriteLine(value);
}

--------
A01
A02
A03
B01
B02
B03
C01
C02
C03
D01
D02
D03

字符等效于C#中的整数,这意味着您可以使用Enumerable.Range生成一个递增整数序列.但是Enumerable.Range将返回整数,这就是为什么需要强制转换回 char 的原因.

Characters are equivalent to integers in C#, which means you can use Enumerable.Range to generate a sequence of increasing integers. Enumerable.Range will return integers though, which is why the cast back to char is required.

您还可以通过从结束字母中减去起始字母来指定要使用的数字或字母,如:

You can also specify the number or letters to use by subtracting the starting letter from the end letter, as shown in this SO question:

var maxLetters = 'D' - 'A' +1;

一旦有了索引序列,就可以使用 foreach 对其进行迭代.

Once you have the sequence of indices, you can iterate over it with foreach.

这篇关于如果循环变量的值是模式LetterNumberNumber的字符串,则为For循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 12:53