Create Items from 3 collections using Linq

Since you’re talking about List<T> (which has a fast indexer), and you provide the guarantee that all three lists are of the same length, the easiest way would be:

var items = from index in Enumerable.Range(0, list1.Count)
            select new Item
            {
                Value1 = list1[index],
                Value2 = list2[index],
                Value3 = list3[index]
            }; 

This approach obviously won’t work well with collections that don’t support fast indexers. A more general approach would be to write a Zip3 method, such as the one that comes with the F# Collections.Seq module: Seq.zip3<'T1,'T2,'T3>. Otherwise, you could chain two Enumerable.Zip calls together to produce similar behaviour (as mentioned in other answers), although this does look quite ugly.

Leave a Comment