如何获得在C#中的连续字符? [英] How to get continuous characters in C#?

查看:352
本文介绍了如何获得在C#中的连续字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有个

List<String> MyList=new List<string>();



我需要填写名单 MYLIST N 值。

如果n的值为2则列表 MYLIST 将包含

if the value of n is 2 then the list MyList will contain

"A","B"

如果10然后

"A","B","C"....."J"

如果30然后

"A"....."Z","AA","AB",AC","AD"

如果1000然后

"A",....."Z","AA","AB"......"AZ","BA","BB"......."BZ"........"YZ","AAA",AAB".....
and so on

我不知道如何做到这一点。

I do not know how to do this.

请帮我这个使用使用任何方法来做 LINQ lambda表达式

Please help me to do this using any method Using LINQ or LAMBDA Expression

推荐答案

修改2

这可能是实现它最简单的方法。我测试了它,它工作正常。你可以生成字符串的无限数量

This is probably the easiest way to implement it. I tested it, it works fine. You could generate a infinite number of strings.

public IEnumerable<string> GenerateStrings()
{
    foreach(string character in Alphabet())
    {
      yield return character;
    }

    foreach (string prefix in GenerateStrings())
    {
      foreach(string suffix in Alphabet())
      {
        yield return prefix + suffix;
      }
    }
}

public IEnumerable<string> Alphabet()
{
    for(int i = 0; i < 26; i++)
    {
      yield return ((char)('A' + i)).ToString();
    }
}






东西我以前写的:


Stuff I wrote before:

您也可以写一个小递归函数返回一个特定的指数的字符串。这可能不是最优的性能明智的,因为有一些重复的部门,但它可能是你的目的不够快。

You could also write a little recursive function which returns any string by a certain index. This may not be optimal performance wise, because there are some repetitive divisions, but it may be fast enough for your purpose.

这是很短,容易:

string GetString(int index)
{
  if (index < 26)
  {
    return ((char)('A' + index)).ToString();
  }
  return GetString(index / 26 - 1) + GetString(index % 26);
}



使用(也可放入另一种方法:

usage (may also be put into another method:

List<string> strings = Enumerable.Range(0, 1000)
  .Select(x => GetString(x))
  .ToList();

这是工作的代码,只是写了一个测试为它

This is working code, just wrote a test for it.

编辑:例如,全LINQ办法的GetString的应用程序:

eg, the "full linq way" application of GetString:

public void IEnumerale<string> GenerateStrings()
{
  int index = 0;
  // generate "infinit" number of values ...
  while (true)
  {
     // ignoring index == int.MaxValue
     yield return GetString(index++);
  }
}

List<string> strings = GenerateStrings().Take(1000).ToList();

这篇关于如何获得在C#中的连续字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆