2

Say I have List<string> FontStyle containing the following

        "a0.png",
        "b0.png",
        "b1.png",
        "b2.png",
        "b3.png", 
        "c0.png",
        "c1.png",
        "d0.png",
        "d1.png",
        "d2.png" 

I want to randomly select a string from the list with its first character matches a certain character. For example if the character is c. The method will returns either c0.png or c1.png randomly.

How do I do this using LINQ?

2 Answers 2

5

This should do the trick:

var random = new Random();
var list = new List<string> {
    "a0.png",
    "b0.png",
    "b1.png",
    "b2.png",
    "b3.png", 
    "c0.png",
    "c1.png",
    "d0.png",
    "d1.png",
    "d2.png" 
};
var startingChar = "d";

var filteredList = list.Where(s => s.StartsWith(startingChar)).ToList();
Console.WriteLine(filteredList.Count);

int index = random.Next(filteredList.Count);
Console.WriteLine(index);

var font = filteredList[index];
Console.WriteLine(font);

but the problem with the entire solution is that the smaller the resulting filtered list is the less likely you are to get really random values. The Random class works much better on much larger constraints - so just keep that in mind.

Sign up to request clarification or add additional context in comments.

6 Comments

sorry, but probably you meant Where instead of Select in the first line
Last line won't compile - filteredList is not a list, it's an IEnumerable<T>. Needs ToList() on the first line.
@KentBoogaart, thanks a lot. I need to get it setup so I can build these little examples in Notepad++ and compile them there. Doesn't Jon Skeet do that?
@Michael: I'm thinking ScriptCS will be perfect for that. Skeet compiles in his head in less time than the C# compiler takes.
@KentBoogaart, thanks a lot for that, I got it installed and rebuilt this example compiled in ScriptCs. Absolutely fantastic!
|
4
Random random = ...;
var itemsStartingWithC = input
    .Where(x => x.StartsWith("c"))
    .ToList();
var randomItemStartingWithC =
    itemsStartingWithC.ElementAt(random.Next(0, itemsStartingWithC.Count()));

The call to ToList isn't strictly necessary, but results in faster code in this instance. Without it, Count() will fully enumerate and ElementAt will need to enumerate to the randomly selected index.

4 Comments

wont this select random char from each string, that start from c?
@Ilya: you're right - I meant ElementAt but typed Select. Corrected.
ElementAt cannot take func
yes, but this is not quite right. x.Count will return the length of the substring, while you are using it inside ElementAt. You need to access Count on a filtered list

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.