使用 Linq 从 3 个集合创建项目 [英] Create Items from 3 collections using Linq

查看:28
本文介绍了使用 Linq 从 3 个集合创建项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 3 个集合,其中的项目数完全相同.

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

我需要根据这 3 个集合项值创建一个新集合.

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

示例:

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;}
}

我尝试使用 Linq 来实现这一点.

I try to achieve this using Linq.

我试过了:

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

但是我遇到了 OutOfMemoryException,我的 3 个列表很大.

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

有什么帮助吗?

推荐答案

既然你在谈论 List(它有一个快速的索引器),你保证所有三个列表长度相同,最简单的方法是:

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]
            }; 

这种方法显然不适用于不支持快速索引器的集合.一种更通用的方法是编写一个 Zip3 方法,例如随 F# Collections.Seq 模块提供的方法:Seq.zip3<'T1,'T2,'T3>.否则,您可以链接两个 Enumerable.Zip 调用在一起以产生类似的行为(如其他答案中所述),尽管这看起来很丑陋.

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.

这篇关于使用 Linq 从 3 个集合创建项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆