-
Helenr
首先,您应该将变量的值移动到如下所示的字典结构中var tbl = new Dictionary<string, string>() { { "70V", "1,2,3,4" }, { "100V", "10,20,30,40" }, { "25V", ".2,.4,.6,.8" },};然后您可以使用以下代码轻松查询它tbl.SelectMany(x => x.Value.Split(',').Select(y => $"{y} Watt {x.Key}"));该SelectMany调用展平了多层层次结构,并返回IEnumerable<string>带有所需字符串的 。对于内插字符串的$"{y}"语法,如果您不使用受支持的 C# 版本,则可以使用string.Format而不是字符串内插更新根据 OP 的评论,我提供了一种形成上面字典的方法var tbl = new Dictionary<string, string>() { { nameof(Tap70V), Tap70V }, { nameof(Tap100V), Tap100V }, { nameof(Tap25V), Tap25V },};依赖变量名来获取值是一种危险的做法。如果 OP 提供了 和 的值如何可用70V,那么我可以用合适的方式更新答案以使其适应该解决方案100V25V
-
哆啦的时光机
问题是:你怎么知道值的范围与 70V 有关,而值的范围与 25V 有关?但让我们假设您有一系列电压文本组合:Voltage | Text 70 | "1,2,3,4" 100 | "10,20,30,40" 25 | ".2,.4,.6,.8"例如,从您的三个变量创建它们:IEnumerable<VoltageTextCombination> voltageTextCombinations = new VoltageTextCombination[]{ new VoltageTextCombination {Voltage = 70, Text = Tap70V}, new VoltageTextCombination {Voltage = 100, Text = Tap100V}, new VoltageTextCombination {Voltage = 25, Text = Tap25V},}我为此定义了一个类 VoltageTextCombination。当然,您也可以为此使用匿名类型。要获得您的组合框项目序列,您需要将文本拆分为一系列瓦特,并使用正确的SelectMany 重载来获得一系列电压 - 瓦特组合。之后,您使用 String.Format 将每个电压 - 瓦特组合转换为您想要显示的文本:下面的 LINQ 中使用的常量,用于将输入文本拆分为瓦特,并将电压 - 瓦特组合格式化为字符串:static readonly char[] separatorChars = new char[] {','};const string strFormat ="{0} Watt {1}V";LINQ 查询:var result = voltageTextCombinations.SelectMany( // parameter collectionSelector: // input a source element (= one voltageTextCombination) // output a sequence (= the text of the combination split into Watts combination => combination.Text.Split(separatorChars), // parameter resultSelector: take one source element, and one of every watt // to make a Voltage - Watt combination (voltageTextCombi, splitString) => new { Voltage = voltageTextCombi.Voltage, Watt = splitString, }) // convert every Voltage-Watt combination to one string: .Select(voltageWattCombi => String.Format(strFormat, voltageWattCombi.Watt, voltageWattCombi.Voltage));非常简单!
-
元芳怎么了
这是我能想到的最干净的方法来完成我的问题:if (value is IItemLibrarySpeaker s) { List<string> taps = s.Speaker25VTaps.Split(',').Select(x => $"{x} Watt/25V").ToList(); taps.AddRange(s.Speaker70VTaps.Split(',').Select(x => $"{x} Watt/70V")); taps.AddRange(s.Speaker100VTaps.Split(',').Select(x => $"{x} Watt/100V")); return taps; }感谢您的建议(即使是与我的问题无关的建议)
-
喵喵时光机
根据提供的示例数据,我制作了如下示例代码:string Tap70V = "1,2,3,4"; //example data string Tap100V = "10,20,30,40"; //example data string Tap25V = ".2,.4,.6,.8"; //example data var test = new List<string>(); test.AddRange(Tap70V.Split(',').Select(val => val + " Watt 70V")); test.AddRange(Tap100V.Split(',').Select(val => val + " Watt 100V")); test.AddRange(Tap25V.Split(',').Select(val => val + " Watt 25V"));在上面的代码中,将字符串对象值添加到List<string>变量 namedtest中。对于每个对象数据都需要拆分并添加范围到列表中。