mardi 26 mars 2019

How to find a random item from a C# list that has a specific value?

I'm trying to find an item from a list that has a field with a specific value; some entries will have the same value for this field, and in that case, I would like to return one of those at random. Does the List.Find function return one randomly if there are multiple entries that satisfy the criteria? The code below is what I currently have; if used on the same list multiple times, will it return the same entry every time if multiple satisfy the criteria? The list is large enough that I would prefer not to foreach through, build a list of everything that meets the criteria, and then randomly return one of those; I'm hoping to find a more efficient way. If that's not feasible for a List, is there another data structure more suited to this?

public List<Category> Categories {get; set;}

public Category CatByName(string nm)
        {
            string name = nm.ToUpper();
            return Categories.Find(x => x.CategoryName.Contains(name));
        }




Aucun commentaire:

Enregistrer un commentaire