简体   繁体   English

连接对象数组的字段值

[英]concat field values of an array of objects

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 += ",";
    }
}

What is the linq manner to do this or is there a string's method ? LINQ的方式是什么?有没有字符串的方法?

像这样尝试linq:

string.Join(",", this._previousDayPrices.Take(2).Select(d => string.Format("{0}-{1}-{2}-{3}", d.Price, d.Date,d.EuroExchangeRateDate, d.EuroExchangeRate)).ToArray());

That's the way your code may be improved 这就是可以改善您的代码的方式

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);
    }
}

Try 尝试

        var result = string.Join(",", (from d in _previousDayPrices.Take(2) select 
               string.Join("-", {d.Price, 
                                 d.Date, 
                                 d.EuroExchangeRateDate,
                                 d.EuroExchangeRate})).ToArray());

This assumes that Price, Date, EuroExchangeRateDate and EuroExchangeRate are already strings (I doubt that based upon their names, but your sample points in this direction). 假设Price,Date,EuroExchangeRateDate和EuroExchangeRate已经是字符串(我怀疑基于它们的名称,但是您的示例指向这个方向)。 If not, you need to convert them before. 如果不是,则需要先进行转换。

Try it , 试试吧 ,

var res = _previousDayPrices.Take(2).Aggregate((i,j) => i.Price + "-" + i.Date + "-" + i.EuroExchangeRateDate +"-" + i.EuroExchangeRate + "," + 
        j.Price + "-" + j.Date + "-" + j.EuroExchangeRateDate +"-" + j.EuroExchangeRate +
        )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM