从表2场选择并加入他们作为字符串
问题描述:
我有类Product
从表2场选择并加入他们作为字符串
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
获得这样的对象)。
答
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)))
答
一种可能的方法:
覆盖ToString()
功能Product
类:(只执行)
return string.Format("{0}({1})", Name, Quantity);
然后写:
string.join (",", products.Select(p => p.ToString()));
谢谢,实在想不出它是如此容易 – user3625486 2014-12-06 21:49:35