Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

c# - Create Items from 3 collections using Linq

I've 3 collections with exactly the same items count.

I need to create a new collection based on these 3 collections item values.

Exemple :

List<double> list1;
List<double> list2;
List<double> list3;

List<Item> list4;

public class Item
{
   public double Value1{get;set;}
   public double Value2{get;set;}
   public double Value3{get;set;}
}

I try to achieve this using Linq.

I tried :

    var query = from pt in list1
                from at in list2
                from ct in list3
                select new Item
                           {
                               Value1 = pt,
                               Value2 = at,
                               Value3 = ct
                           };

But i got a OutOfMemoryException, my 3 lists are huge.

Any help ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...