private readonly List<A> _previousDayPrices;
private void PrintDebugPreviousDayPrice(DateTime date)
{
var str = "";
foreach (var d in _previousDayPrices.Take(2))
{
str += d.Price;
str += "-";
str += d.Date;
str += "-";
str += d.EuroExchangeRateDate;
str += "-";
str += d.EuroExchangeRate;
str += ",";
}
}
执行此操作的linq方式是什么,或者是否有字符串的方法?
答案 0 :(得分:4)
尝试这样的linq:
string.Join(",", this._previousDayPrices.Take(2).Select(d => string.Format("{0}-{1}-{2}-{3}", d.Price, d.Date,d.EuroExchangeRateDate, d.EuroExchangeRate)).ToArray());
答案 1 :(得分:0)
这是您的代码可以改进的方式
private readonly List<AnItemType> _previousDayPrices;
private void PrintDebugPreviousDayPrice(DateTime date)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (AnItemType item in _previousDayPrices)
{
String valueToAppend = String.Format(
"{0}-{1}-{2}-{3},",
item.Price,
item.Date,
item.EuroExchangeRateDate,
item.EuroExchangeRate);
stringBuilder.Append(valueToAppend);
}
}
答案 2 :(得分:0)
尝试
var result = string.Join(",", (from d in _previousDayPrices.Take(2) select
string.Join("-", {d.Price,
d.Date,
d.EuroExchangeRateDate,
d.EuroExchangeRate})).ToArray());
这假设Price,Date,EuroExchangeRateDate和EuroExchangeRate已经是字符串(我怀疑这是基于他们的名字,但你的样本指向这个方向)。如果没有,您需要先转换它们。
答案 3 :(得分:0)
试试吧,
var res = _previousDayPrices.Take(2).Aggregate((i,j) => i.Price + "-" + i.Date + "-" + i.EuroExchangeRateDate +"-" + i.EuroExchangeRate + "," +
j.Price + "-" + j.Date + "-" + j.EuroExchangeRateDate +"-" + j.EuroExchangeRate +
)