如何将list<byte[], int>和list<tuple<byte[], int>>转换为list<byte[]>
Hey there! Let's walk through how to handle both of these conversion scenarios in C#—they're actually pretty straightforward once you know how to use LINQ's projection capabilities.
处理值元组列表(List<(byte[], int)>)
If you're working with C# value tuples (the newer, cleaner (T1, T2) syntax), you can use the Select method from LINQ to pluck out just the byte[] element from each tuple entry.
Here's a quick example:
using System.Linq; // Your original list of value tuples List<(byte[], int)> originalValueTupleList = new List<(byte[], int)>(); // Convert to List<byte[]> by selecting the first element of each tuple List<byte[]> byteArrayList = originalValueTupleList.Select(item => item.Item1).ToList();
If you're using named value tuples (like (byte[] Data, int Counter)), you can make the code even more readable by using the property name instead of Item1:
List<(byte[] Data, int Counter)> namedTupleList = new List<(byte[] Data, int Counter)>(); List<byte[]> readableResult = namedTupleList.Select(item => item.Data).ToList();
处理传统Tuple列表(List<Tuple<byte[], int>>)
For the older Tuple<T1, T2> type (the one where you explicitly use the Tuple class), the approach is almost identical—you still use Select, but you access the first element via the Item1 property of the Tuple object.
Example code:
using System.Linq; using System; // Required for the Tuple class // Your original list of traditional Tuples List<Tuple<byte[], int>> originalTupleList = new List<Tuple<byte[], int>>(); // Extract just the byte[] elements List<byte[]> resultByteArrayList = originalTupleList.Select(tuple => tuple.Item1).ToList();
Quick Note
Don't forget to add a reference to System.Linq (via the using directive) since we're using LINQ methods here. This works in all modern C# versions (C# 3.0 and above for LINQ, C# 7.0+ for value tuples).
内容的提问来源于stack exchange,提问作者patrick

