Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return list of specific property of object using linq

Given a class like this:

public class Stock {     public Stock() {}     public Guid StockID { get; set; }     public string Description { get; set; } } 

Lets say I now have a List<Stock>. If I would like to retrieve a list of all the StockIDs and populate it into a IEnumerable or IList. Obviously I can do this.

List<Stock> stockItems = new List<Stock>(); List<Guid> ids = new List<Guid>();  foreach (Stock itm in stockItems)  {     ids.Add(itm.StockID); } 

But is there some way I could use Linq to achieve the same result? I thought Distinct() might do it but couldn't work out how to achieve the desired result.

like image 977
Maxim Gershkovich Avatar asked Jul 20 '12 06:07

Maxim Gershkovich


People also ask

What a LINQ query returns in LINQ to object?

Language-Integrated Query (LINQ) makes it easy to access database information and execute queries. By default, LINQ queries return a list of objects as an anonymous type. You can also specify that a query return a list of a specific type by using the Select clause.

Which LINQ method returns a single object?

You can use the SingleOrDefault method if you are sure there will be only a single item or null yields from your where condition.

What does LINQ any return?

What is Linq Any in C#? The C# Linq Any Operator is used to check whether at least one of the elements of a data source satisfies a given condition or not. If any of the elements satisfy the given condition, then it returns true else return false. It is also used to check whether a collection contains some data or not.

What is the return type of Where in LINQ?

There are only two return types for a Linq query. It's either a single concrete object or a single anonymous type object that is returned. It can also be a List<T> of concrete objects or anonymous type objects that are returned in a collection.


2 Answers

var list = stockItems.Select(item => item.StockID).ToList(); 
like image 120
Amiram Korach Avatar answered Oct 05 '22 13:10

Amiram Korach


You could also do it like this:

ids = stockItems.ConvertAll<Guid>(o => o.StockID); 
like image 44
Ivan Golović Avatar answered Oct 05 '22 12:10

Ivan Golović