-4

I need to get non repetitive alphanumeric character in 10 digit using LINQ. I searched google a lot. But i could not able to find it out. Please help me to get the solution. Thanks

Vetri
  • 71
  • 8

2 Answers2

1

If you don't have to use linq

var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var stringChars = new char[10];
var random = new Random();

for (int i = 0; i < stringChars.Length; i++)
{
    var randomNumber = random.Next(chars.Length);
    stringChars[i] = chars[randomNumber];
    chars = chars.Replace(chars[randomNumber].ToString(), "");
}

var finalString = new String(stringChars);
Liviu Boboia
  • 1,734
  • 1
  • 10
  • 21
0

It is a very interesting LINQ question... Probably by using Aggregate it is solvable...

Mmmh... yes... it is evil enough:

var rnd = new Random();
var chars = "ABCDEFGHIJ0123456789";
var res = Enumerable.Range(0, 10)
    .Select(x => rnd.Next(0, chars.Length - x))
    .Aggregate(
        Tuple.Create(string.Empty, chars), 
        (prev, ix) => Tuple.Create(
            prev.Item1 + prev.Item2[ix], 
            prev.Item2.Substring(0, ix) + prev.Item2.Substring(ix + 1)
        )
    ).Item1;

In general using LINQ is wrong here, because every character depends on all the previous characters. This is complex to do in LINQ. I had to cheat heavily, using the .Aggregate() and keeping a "state" of all the unused characters (the Item2) and adding the characters for the "response" to the Item1.

xanatos
  • 109,618
  • 12
  • 197
  • 280