mercredi 14 février 2018

c# pass class variable as paramater in method LINQ like?

I have a class with a lot of different string values

I have a collection class holding these with some sorting functions. Currently i have lots of reproduced code for "GetListOfDifferentProducts" "GetListOfDifferentManufacturers" etc.

Is this possible? Or am i going about this the wrong way.

These are all simple foreach loops

        public List<string> GetListOfDifferentProducts()
    {
        List<string> listOfResults = new List<string>();
        foreach (Product prod in listOfProducts)
        {
            if (listOfResults.Contains(prod.Name.ToLower()) == false)
                listOfResults.Add(prod.Name.ToLower());
        }
        return listOfResults;
    }

I'd like to pass in a class variable (Like LINQ?)

    public List<string> GetListOfDifferentVariables(variableType)
    {
        List<string> listOfResults = new List<string>();
        foreach (Product prod in listOfProducts)
        {
            if (listOfResults.Contains(prod.variableType.ToLower()) == false)
                listOfResults.Add(prod.variableType.ToLower());
        }
        return listOfResults;
    }

example Usage:

ProductList.GetListOfDifferentVariables(o => o.Name);





Aucun commentaire:

Enregistrer un commentaire