You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将元组列表转换为列表元组?基于System.Linq的高效实现

高效拆分IEnumerable<(int, char)>为(IEnumerable<int>, IEnumerable<char>)的实现方案

基于System.Linq的简洁实现

直接通过Select分别提取元组的两个元素,这是最符合Linq风格的实现:

var (ints, chars) = (list.Select(x => x.Item1), list.Select(x => x.Item2));

这种方式采用延迟执行逻辑,只有当你实际遍历ints或chars时才会处理原集合,不会提前占用内存存储所有元素,适合可多次枚举的数据源(比如List<(int, char)>)。

避免多次枚举的高效实现

如果原集合是只能枚举一次的类型(比如数据库查询结果、流式数据),上面的方式会导致原集合被遍历两次(分别遍历两个结果集合时),此时可以用一次性遍历的方案,将元素同时存入两个集合:

var intList = new List<int>();
var charList = new List<char>();
foreach (var (i, c) in list)
{
    intList.Add(i);
    charList.Add(c);
}
var result = (intList.AsEnumerable(), charList.AsEnumerable());

该方案仅遍历原集合一次,代价是需要提前将所有元素加载到内存中。

可复用的自定义扩展方法

如果需要频繁执行这类拆分操作,可以封装成Linq扩展方法:

public static (IEnumerable<T1>, IEnumerable<T2>) Unzip<T1, T2>(this IEnumerable<(T1, T2)> source)
{
    var list1 = new List<T1>();
    var list2 = new List<T2>();
    foreach (var item in source)
    {
        list1.Add(item.Item1);
        list2.Add(item.Item2);
    }
    return (list1, list2);
}

// 使用方式
var (ints, chars) = list.Unzip();

总结:优先使用第一种Linq方案,仅当数据源不能多次枚举时,再选择一次性遍历的实现。

内容的提问来源于stack exchange,提问作者BrandonStudio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 09:03:48