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

by Naveen 25. March 2011 04:03

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();
}
 

Views: 1589

Tags:

LINQ

blog comments powered by Disqus

Smart Phones Poll

What smart phone do you currently own?





Show Results

Month List

Powered by BlogEngine.NET 2.0.0.49
Theme by Naveen Kohli