Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为幸运数字生成唯一字符串_C# - Fatal编程技术网

C# 为幸运数字生成唯一字符串

C# 为幸运数字生成唯一字符串,c#,C#,可能重复: 我必须生成一个随机的唯一字符串。其目的是在表中的每个成功条目后生成一个幸运数字 我不喜欢使用GUID,因为它介于破折号(-)之间。 但它似乎也太长了 我想生成一个大约有10个字符的字符串 任何好主意都将不胜感激。 Cheers您可以创建Guid的字符串表示形式,而不使用破折号: Guid.NewGuid().ToString("N"); 当然,它的长度是32个字符,而不是10个字符。但这是一个简单而快速的解决方案。您可以尝试以下方法: public struct ShortGui

可能重复:

我必须生成一个随机的唯一字符串。其目的是在表中的每个成功条目后生成一个幸运数字

我不喜欢使用GUID,因为它介于破折号(-)之间。 但它似乎也太长了

我想生成一个大约有10个字符的字符串

任何好主意都将不胜感激。
Cheers

您可以创建Guid的字符串表示形式,而不使用破折号:

Guid.NewGuid().ToString("N");
当然,它的长度是32个字符,而不是10个字符。但这是一个简单而快速的解决方案。

您可以尝试以下方法:

public struct ShortGuid
{
    private Guid _underlyingGuid;

    public ShortGuid(Guid underlyingGuid) : this()
    {
        _underlyingGuid = underlyingGuid;
    }

    public static ShortGuid Empty 
    {
        get { return ConvertGuidToShortGuid(Guid.Empty); }
    }

    public static ShortGuid NewShortGuid()
    {
        return ConvertGuidToShortGuid(Guid.NewGuid());
    }

    private static ShortGuid ConvertGuidToShortGuid(Guid guid)
    {
        return new ShortGuid(guid);
    }

    public override string ToString()
    {
        return Convert.ToBase64String(_underlyingGuid.ToByteArray()).EscapeNonCharAndNonDigitSymbols();
    }

    public bool Equals(ShortGuid other)
    {
        return other._underlyingGuid.Equals(_underlyingGuid);
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (obj.GetType() != typeof (ShortGuid)) return false;
        return Equals((ShortGuid) obj);
    }

    public override int GetHashCode()
    {
        return _underlyingGuid.GetHashCode();
    }
}
其中,转义非字符和非数字符号是一种扩展方法:

    public static string EscapeNonCharAndNonDigitSymbols(this string str)
    {
        if (str == null)
            throw new NullReferenceException();
        var chars = new List<char>(str.ToCharArray());

        for (int i = str.Length-1; i>=0; i--)
        {
            if (!Char.IsLetterOrDigit(chars[i]))
                chars.RemoveAt(i);
        }
        return new String(chars.ToArray());
    }
公共静态字符串EscapeNoncharand非数字符号(此字符串str)
{
如果(str==null)
抛出新的NullReferenceException();
var chars=新列表(str.ToCharArray());
对于(int i=str.Length-1;i>=0;i--)
{
if(!Char.isleterordigit(chars[i]))
chars.RemoveAt(i);
}
返回新字符串(chars.ToArray());
}

就在昨天,我不得不做同样的任务。给你:

public static class RandomStringService
{
    //Generate new random every time used. Must sit outside of the function, as static, otherwise there would be no randomness.
    private static readonly Random Rand = new Random((int)DateTime.Now.Ticks);


    /// <summary>
    /// Create random unique string- checking against a table
    /// </summary>
    /// <returns>Random string of defined length</returns>
    public static String GenerateUniqueRandomString(int length)
    {
        //check if the string is unique in Barcode table.
        String newCode;
        do
        {
            newCode = GenerateRandomString(length);

         // and check if there is no duplicates, regenerate the code again.
        } while (_tableRepository.AllRecords.Any(l => l.UniqueString == newCode));

//In my case _tableRepository is injected via DI container and represents a proxy for 
//EntityFramework context. This step is not really necessary, most of the times you can use 
//method below: GenerateRandomString

        return newCode;
    }




    /// <summary>
    /// Generates the random string of given length.
    /// String consists of uppercase letters only.
    /// </summary>
    /// <param name="size">The required length of the string.</param>
    /// <returns>String</returns>
    private static string GenerateRandomString(int size)
    {
        StringBuilder builder = new StringBuilder();
        char ch;
        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(CreateRandomIntForString());
            builder.Append(ch);
        }
        return builder.ToString();
    }



    /// <summary>
    /// Create a random number corresponding to ASCII uppercase or a digit
    /// </summary>
    /// <returns>Integer between 48-57 or between 65-90</returns>
    private static int CreateRandomIntForString()
    {
        //ASCII codes
        //48-57 = digits
        //65-90 = Uppercase letters
        //97-122 = lowercase letters

        int i;
        do
        {
            i = Convert.ToInt32(Rand.Next(48, 90));
        } while (i > 57 && i < 65);

        return i;
    }
公共静态类服务
{
//每次使用时生成新的随机数。必须位于函数外部,作为静态,否则将不会有随机性。
private static readonly Rand=new Random((int)DateTime.Now.Ticks);
/// 
///创建随机唯一字符串-对照表进行检查
/// 
///定义长度的随机字符串
公共静态字符串生成器niquerandoString(int-length)
{
//检查条形码表中的字符串是否唯一。
字符串新代码;
做
{
newCode=GeneratorDomainString(长度);
//并检查是否没有重复,重新生成代码。
}while(_tableRepository.AllRecords.Any(l=>l.UniqueString==newCode));
//在我的例子中,tableRepository是通过DI容器注入的,它代表
//EntityFramework上下文。这个步骤实际上不是必需的,大多数情况下您可以使用它
//下面的方法:GeneratorDomainString
返回新代码;
}
/// 
///生成给定长度的随机字符串。
///字符串仅由大写字母组成。
/// 
///字符串的所需长度。
///串
专用静态字符串生成器DOMSTRING(整数大小)
{
StringBuilder=新的StringBuilder();
char ch;
对于(int i=0;i57&&i<65);
返回i;
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Security.Cryptography;
名称空间LinqRandomString
{
班级计划
{
静态void Main(字符串[]参数)
{
做
{
字节[]随机=新字节[10000];
使用(var rng=RandomNumberGenerator.Create())
rng.GetBytes(随机);
var q=随机
.Where(i=>(i>=65&&i=97&&i Convert.ToChar(i));//转换为字符
foreach(q中的var c)
控制台。写入(c);
}while(Console.ReadLine()!=“退出”);
}
}
}

是的,我可以这样做。但对于这个目的来说,它仍然太长。“似乎太长”很难成为发布另一个问题的理由。这是什么?独特性如何测量?它是否必须是唯一的,仅用于程序的一次运行?或用于一台机器上的所有运行?或用于世界上所有机器上的所有运行?需要更多的上下文!这一个将为您提供18个字符,例如:0ulpp0hecpquj8ttgat它们当然是非常无聊的十六进制数。而且长了3.2倍,甚至更无聊。有时“无聊”是最好的解决方案。嗯?请解释一下。你的意思是,它可以用较少的笔划来完成吗?当然可以,毫无疑问。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace LinqRandomString
{
    class Program
    {
        static void Main(string[] args)
        {
            do
            {
                byte[] random = new byte[10000];

                using (var rng = RandomNumberGenerator.Create())
                    rng.GetBytes(random);


                var q = random
                            .Where(i => (i >= 65 && i <= 90) || (i >= 97 && i <= 122)) // ascii ranges - change to include symbols etc
                            .Take(10) // first 10
                            .Select(i => Convert.ToChar(i)); // convert to a character

                foreach (var c in q)
                    Console.Write(c);

            } while (Console.ReadLine() != "exit");
        }
    }
}