从列表 2 字段中进行选择,并将它们作为字符串连接起来

本文关键字:起来 连接 字符串 字段 列表 选择 行选 | 更新日期: 2023-09-27 18:33: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 来获取此类对象)。

从列表 2 字段中进行选择,并将它们作为字符串连接起来

String.Join(", ", list.Select(p => String.Format("{0}({1})", p.Name, p.Quantity)))
string.Join(", ", products.Select(p=>string.Format("{0}({1})",p.Name, p.Quantity)))

一种可能的方法:

重写类Product ToString()函数:(仅限实现)

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

然后写:

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