c# - 如何将元组列表转换为列表元组?

标签 c# generics collections tuples deconstructor

例如,我有一个 IEnumerable<(int, char)> list .如何转换list进入(IEnumerable<int>, IEnumerable<char>)

有没有快速的方法来做到这一点?使用System.Linq会更好.

最佳答案

聚合非常简单:

IEnumerable<(int, char)> list = new[]
{
    (1, 'a'), (2, 'b'),
};

(List<int> ints, List<char> chars) =
    list.Aggregate((new List<int>(), new List<char>()), (a, x) =>
    {
        a.Item1.Add(x.Item1);
        a.Item2.Add(x.Item2);
        return a;
    });

这给出了:

output

这是最快的方法,但这个更简单:

List<int> ints = list.Select(x => x.Item1).ToList();
List<char> chars = list.Select(x => x.Item2).ToList();

关于c# - 如何将元组列表转换为列表元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73244842/

相关文章:

c# - 发送到 Azure 事件中心错误

c# - 获取属性的值

java - 从不同地方调用时不能在方法参数中使用 List<Future<?>>

Java 泛型 NullPointerException

c# - 我什么时候应该在 IEnumerable<T> 的上下文中使用 .Count() 和 .Count

java - Collections.sort() 不适用于自定义对象

c# - 可空结构的 IEqualityComparer

c# - 将 `unsafe` 关键字应用于 C# 中的 lambda 表达式

java - 在 Java 中显示树层次结构及其值

c# - yield 、 FindAll 和局部变量之间的比较