c# - Linq - 如何映射(选择)解构的元组?
问题描述
我正在努力实现一件非常简单的事情。我有一个 Enumerable 元组,我想同时映射和解构它们(因为 using .Item1
,.Item2
是丑陋的地狱)。
像这样的东西:
List<string> stringList = new List<string>() { "one", "two" };
IEnumerable<(string, int)> tupleList =
stringList.Select(str => (str, 23));
// This works fine, but ugly as hell
tupleList.Select(a => a.Item1 + a.Item2.ToString());
// Doesn't work, as the whole tuple is in the `str`, and num is the index
tupleList.Select((str, num) => ...);
// Doesn't even compile
tupleList.Select(((a, b), num) => ...);
解决方案
您可以命名元组成员:
List<string> stringList = new List<string>() { "one", "two" };
// use named tuple members
IEnumerable<(string literal, int numeral)> tupleList =
stringList.Select(str => (str, 23));
// now you have
tupleList.Select(a => a.literal + a.numeral.ToString());
// or
tupleList.Select(a => $"{a.literal}{a.numeral}");
推荐阅读
- kubernetes - Istio 如何将 Tracing spans 发送到 jaeger?
- assembly - AT&T - reading file
- google-maps - gmaps.places_radar googlemaps.exceptions.HTTPError:HTTP 错误:404
- python - 使用 tf.nn.softmax 而不是 tf.argmax 预测概率的问题
- visual-studio-code - Visual Studio Code 不记得打开的文件/不记得“打开方式”文件
- java - java Codingbat notAlone — why doesn't it work for this specific example
- android - 如何创建 Lint 检查以确保附加了 Activity/Fragment?
- django - Django Group Permissions in React
- c - Find invalid bz2 file preferable using C/C++
- python - 我的问题是关于二进制搜索的实现