首页 > 解决方案 > 希望将所有对象列表组合成单个字符串

问题描述

我有以下课程

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)

任何人都可以让我知道有关如何从列表中获得上述所需格式的任何想法或建议,非常感谢。

标签: c#.net

解决方案


为了处理转换为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)})"));

推荐阅读