Select a matching string randomly from a list using LINQ - c#

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?

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.

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.

Related

Simple LINQ in string list

A little question for a simple LINQ request. This is my first time with LINQ and still not understand all mechanism.
My structure is something like this
List<string> baseData = new List<string>{"\"10\";\"Texte I need\";\"Texte\"",
"\"50\";\"Texte I need\";\"Texte\"",
"\"1000\";\"Texte I need\";\"Texte\"",
"\"100\";\"Texte I need\";\"Texte\""};
Each line of data is construct with field separator ";" and each field are encapsule with quote ".
I have another List Compose with value i have to find in my first list. And i have the Position in line i have to search. because "Texte I need" can be equal with value i am searching
List<string> valueINeedToFind = new List<string>{"50","100"};
char fieldSeparator = ';';
int fieldPositionInBaseDataForSearch = 0;
int fieldPositionInBaseDataToReturn = 1;
I made a first Linq to extract only Line interested me.
List<string> linesINeedInAllData = baseData.Where(Line => valueINeedToFind.Any(Line.Split(fieldSeparator)[fieldPositionInBaseDataForSearch].Trim('"').Contains)).ToList();
This first request Work Great and now i have only Data Line Interested me.
My problem is I don't want all the line But only a list of the value "Texte I need" in position FieldPositionInBaseDataToReturn.
I have to made another LINQ or can i modify my first to directly get what I need?
Since you will be using the split version of each line more than once, separate out the Split operation and then work on the resulting array:
List<string> linesINeedInAllData = baseData.Select(Line => Line.Split(fieldSeparator))
.Where(splitLine => valueINeedToFind.Any(splitLine[fieldPositionInBaseDataForSearch].Trim('"').Contains))
.Select(splitLine => splitLine[fieldPositionInBaseDataToReturn])
.ToList();
List<string> linesINeedInAllData = baseData.Where(Line => valueINeedToFind.Any(Line.Split(fieldSeparator)[fieldPositionInBaseDataForSearch].Trim('"').Equals)).ToList()
.Select(Line => Line.Split(fieldSeparator)[fieldPositionInBaseDataToReturn].Trim('"').ToList();

Determine if an element in a list contains the same value

I have a List containing a number of Guid's.
List<Guid> recordIds = new List<Guid>;
I need to verify if the Guid's in this list are all identical.
So instead of iterating the whole list I was thinking about using some sort of:
var IdsAreIdentical = recordIds.TrueForAll(x => x == DontKnowWhatToPutHere);
My issue is that I am not really shure about the usage. Maybe somebody can put me in the right direction.
If you want to verify if all the id are the same, you could verify that all the values are the same as the first one :
bool allIdentical = recordIds.TrueForAll(i => i.Equals(recordIds.FirstOrDefault());
Another variant would be to verify the number of distinct values that you have. If the result is 1, the ids are all identicals.
var allIdentical = list.Distinct().Count() == 1;

Sort a list in c# based on exact match/partial match

I have a list of elements list
1) taymril 6.5% inmatro
2) taymril 11.5% tometo
3) taymril 1.5% romeo
The input string is, for example, taymril 1.5% romeo. How do I sort the above list (15-20 elements but I have written only three as an example) based on a match with the input string? how do I do this in a generic way for all input strings and all elements in the database? any idea?
List<string> listString = new List<string>();
listString.Add("taymril 6.5% inmatro");
listString.Add("taymril 11.5% tometo");
listString.Add("taymril 1.5% romeo");
var list = listString.OrderBy(x => x);
//or
var listd = listString.OrderByDescending(x => x);

how to get random amount of details from a list or var in c#

I'm reading result from an json file inside the local project.it returns more than 4000 result.I want to get only random number of results (between 500- 1000) from that result.
var finalResultz = finalResults("All","All","All");//step one
in here it returns more than 4000 results.then I put into a list like this.
List<Results> searchOne = new List<Results>();//step two
foreach(var itms in finalResultz)
{
searchOne.Add(new Results
{
resultDestination = returnRegionName(itms.areaDestination),
mainImageurl = itms.testingImageUrl
});
}
ViewBag.requested = searchOne;
but I want to get only the results like I said.I want to resize the count in step one or in step two.how can I do that.hope your help.
If you want a random count of results, you can just .Take() a random number of the records. First, you'll need a Random:
var random = new Random();
If you want between 500-1000, just get a random value in that range:
var count = random.Next(500, 1001);
Then you can take those records from the collection:
var newList = oldList.Take(count).ToList();
(Of course, you may want to make sure it contains that many records first.)
Note that this will take the first N records from the collection. So in order to take random records from anywhere in the collection, you'd need to shuffle (randomize) the collection before taking the records. There are a number of ways you can do that. One approach which may not be the absolute fastest but is generally "fast enough" for simplicity is to just sort by a GUID. So something like this:
var newList = oldList.OrderBy(x => Guid.NewGuid()).Take(count).ToList();
Or maybe use the randomizer again:
var newList = oldList.OrderBy(x => random.Next()).Take(count).ToList();
You can use Random class and Take() method to extract N elements.
// create new instance of random class
Random rnd = new Random();
// get number of elements that will be retrieved from 500 to 1000
var elementsCount = rnd.Next(500, 1000);
// order source collection by random numbers and then take N elements:
var searchOne = finalResultz.OrderBy(x => rnd.Next()).Take(elementsCount);

Sorting list of items according to another fixed list

I'm very beginner in C#.
I have a List of
private List<String> mXMLProdcutsIDs = new List<String>();
mXMLProductsIDs is like
{"megapack", "levelpack","bikepack"}.
Sometimes I get another list which is in random order, {"megapack", "levelpack","bikepack"}
I would like to resort that list according to the mXMLProductIDs list order
You can use index of string in original list to define items order:
var result = anotherList.OrderBy(s => mXMLProdcutsIDs.IndexOf(s));
Shorten version:
var result = anotherList.OrderBy(mXMLProdcutsIDs.IndexOf);
Keep in mind, that result will be IEnumerable<string>. You can use ToList() if you need to save results in list.
Another option (if you don't have duplicated items in another list):
var result = mXMLProdcutsIDs.Intersect(anotherList);

Categories