Linq Tips - Get Array Of One Property Of Class With Linq

If you have a collection of class object and you want to extract an array or list of only one of the properties, lot of time we end up writing code that iterates over each item and then putting it in a new array or list. There is a clean and quick way of doing it using Linq. Following code snippet shows how I extracted an array of ingredient names from a List of Ingredient class objects.

public string[] SearchIngredient(string prefixText, int count)
 var ingredientsList = IngredientData.GetIngredientsWithNameLike(prefixText);
 if (null == ingredientsList ||
     ingredientsList.Count == 0)
  {return null;}

 var nameQuery = from ingredient in ingredientsList
                   select ingredient.Name;
 return nameQuery.ToArray();




8.9 °C / 48.1 °F

weather conditions Clouds

Monthly Posts

Blog Tags