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
Asked
Active
Viewed 71 times
-4
-
you need to get 10 distinct random alphanumeric characters? – Liviu Boboia Apr 11 '17 at 12:04
-
2Please show us what you've tried, and where exactly you run into problems. – Frauke Apr 11 '17 at 12:04
-
You need to get it from what? – Rufus L Apr 11 '17 at 12:04
-
And I don't see how LINQ will help generating a pseudorandom string :-) – xanatos Apr 11 '17 at 12:05
-
Why must you use LINQ? – Richard Apr 11 '17 at 12:05
-
Sounds like what you really need is to use a stringbuilder and append characters mapped to a random number generator. – Mad Myche Apr 11 '17 at 12:11
-
the first answer here generates a random string using linq, you just need to add some code to make the characters disctinct http://stackoverflow.com/questions/1344221/how-can-i-generate-random-alphanumeric-strings-in-c – Liviu Boboia Apr 11 '17 at 12:12
-
I was trying in LINQ, thats why i mentioned like using LINQ. – Vetri Apr 11 '17 at 12:13
2 Answers
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
-
You'll need an inner cycle to avoid all the `\0` you are adding to your `chars` string... and the `Replace` doesn't modify the original string (strings are immutable in .NET), so `chars = chars.Replace(` – xanatos Apr 11 '17 at 12:17
-
-
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