c# - 希望将所有对象列表组合成单个字符串
问题描述
我有以下课程
public class ComponentRedundancy
{
public int EquipmentQuantity { get; set; }
public double RedundancyPercentage { get; set; }
public Redundancy Redundancy { get; set; }
}
下面是一个枚举
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum Redundancy
{
[Description("N")]
N,
[Description("N+1")]
N_PLUS_1,
[Description("2N")]
N_MULTIPLY_2
}
我有这些物品
List<ComponentRedundancy> componentRedundancy = new List<ComponentRedundancy>();
componentRedundancy.Add(new ComponentRedundancy(1, 70, N_MULTIPLY_2));
componentRedundancy.Add(new ComponentRedundancy(2, 50, N_PLUS_1));
componentRedundancy.Add(new ComponentRedundancy(3, 40, N));
我正在寻找将所有这些值结合起来,结果会像这样在单行字符串中
[1@70%](2N)[2@50%](N+1)[3@40%](N)
任何人都可以让我知道有关如何从列表中获得上述所需格式的任何想法或建议,非常感谢。
解决方案
为了处理转换为enum
自定义字符串,我们可以编写一个方法:
private static string Convert(Redundancy r)
{
switch (r)
{
case Redundancy.N:
return "N";
case Redundancy.N_MULTIPLY_2:
return "2N";
case Redundancy.N_PLUS_1:
return "N+1";
default:
return string.Empty;
}
}
然后我们可以使用string.Concat
将所有字符串合并为一个,使用Select
为每个项目选择自定义字符串:
string results = string.Concat(componentRedundancy.Select(cr =>
$"[{cr.EquipmentQuantity}@{cr.RedundancyPercentage}%]({Convert(cr.Redundancy)})"));
推荐阅读
- android - 如何知道 gradle , android studio 用于构建 android app
- facebook - Azure BotFramework V4 可以获取 facebook webhook 页面提要事件吗?
- cassandra - Cassandra nodetool 状态下降并且生成时间很旧
- javascript - 在 rails activeadmin 中渲染表单部分而不使用 formtastic 表单
- python - 将许多python变量的列表保存到excel表中,同时保持变量类型的定义?
- flutter - Flutter 中的 MDNS 支持
- c++ - 如何将对象放入`std::tuple`并使用仅移动操作获取第一项?
- android - Android / 阅读所有活动状态栏通知
- ruby-on-rails - 将 ruby 哈希转换为 yaml 时缩进不当
- java - 回收视图适配器我如何在单击时突出显示单个项目