【问题标题】:Select from list 2 fields and join them as string从列表 2 字段中选择并将它们作为字符串加入
【发布时间】:2014-12-06 21:42:18
【问题描述】:

我有课Product

public class Product
{
   public string Name{get;set;}
   public int Quantity{get;set;}
   // and other
}

经过一些操作,我得到List<Product>。

如何从该列表中创建格式为productName1(productQuantity1), productName2(productQuantity2), ... 的字符串?

我应该使用String.Join,但不知道如何将它与一些动态对象或 KeyValuePair 一起使用(如果我使用 Select 来获取此类对象)。

【问题讨论】:

    标签: c# string linq join


    【解决方案1】:
    String.Join(", ", list.Select(p => String.Format("{0}({1})", p.Name, p.Quantity)))
    

    【讨论】:

      【解决方案2】:
      string.Join(", ", products.Select(p=>string.Format("{0}({1})",p.Name, p.Quantity)))
      

      【讨论】:

        【解决方案3】:

        一种可能的方式:

        覆盖Product 类中的ToString() 函数:(仅限实现)

        return string.Format("{0}({1})", Name, Quantity);
        

        然后写:

        string.join (",", products.Select(p => p.ToString()));
        

        【讨论】:

          猜你喜欢
          • 2017-03-21
          • 2022-01-21
          • 1970-01-01
          • 1970-01-01
          • 2014-04-15
          • 1970-01-01
          • 1970-01-01
          • 2021-11-17
          • 2022-01-18
          相关资源
          最近更新 更多