0
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 方式是什么,或者是否有字符串的方法?

4

4 回答 4

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());
于 2013-11-12T08:44:29.127 回答
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);
    }
}
于 2013-11-12T08:44:53.360 回答
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 已经是字符串(我怀疑基于它们的名称,但您的样本指向这个方向)。如果没有,您需要先转换它们。

于 2013-11-12T08:45:24.730 回答
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 +
        )
于 2013-11-12T08:56:33.807 回答