Efficient Method for Creating CSV String from Lists/SortedLists C#?

后端 未结 3 425
伪装坚强ぢ
伪装坚强ぢ 2021-01-27 13:54

I have an application which implements Asynchronous SOAP. Every 50-100ms I will receive data which is converted into a SortedList object. I als

3条回答
  •  不思量自难忘°
    2021-01-27 14:43

    I'm sure I haven't come up with the most efficient algorithm, but here is a starting point, at least. If nothing else, you will notice the use of StringBuilder, rather than concatenating strings. This alone is likely to garner you some performace benefit.

    This algorithm assumes that both the SortedList keys and the "data" List are ordered in the same way (low-to-high).

    var textBuilder = new StringBuilder(timestamp.ToString("HH:mm:ss"));
    
    var index = 0;
    foreach(double key in data.Keys)
    {
        while(Allkeys[index] < key)
        {
            textBuilder.Append(",0.0");
            index++;
        }
    
        textBuilder.Append(",").Append(data[key]);
        index++;
    }
    MyText = textBuilder.Append(@"\n").ToString();
    

    Just looking at the above, I'm sure there is a bug, but not sure what or where without spending more time and/or testing.

    A possible LINQ solution is more declarative:

    var textBuilder = new StringBuilder(timestamp.ToString("HH:mm:ss"));
    
    var values = Allkeys.Select(
        key => data.ContainsKey(key) ? data[key].ToString() : "0.0")
        .ToArray();
    
    var data = String.Join(",", values);
    var MyText = textBuilder.Append(data).Append(@"\n").ToString();
    

    More can be included in the LINQ expression using the Aggregate extension method, but you'd have to use string concatenation in the accumulator, so I haven't shown that here.

提交回复
热议问题