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.
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.
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 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.
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.
var list = stockItems.Select(item => item.StockID).ToList();
You could also do it like this:
ids = stockItems.ConvertAll<Guid>(o => o.StockID);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With