Copy one List to another List in one line of code using Linq and lambdas!

I find it pretty useful to try and incorporate time and code line saving features where it is beneficial to my productivity and the code readability. One thing I need to do often is convert lists from one type to another.

Here is a one liner to convert an object with a VendorID property on it into a List of integers.

var list = (List<VendorInvoice>)Context.Items[“VendorInvoices”];
List<int> intList = new List<int>();
list.ForEach(l => intList.Add(l.VendorInvoiceID));

See the Foreach processes each element of the List using the Lambda. The l variable (you can name it something more useful) is then fed to the function body which is simply an Add to the other list. More complex operations are easily accomplished using the same pattern.

Less code, easy to read.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.