Jam66125
Jam66125

Reputation: 163

Create an IEnumerable Queue from two IEnumerables

I have two IEnumerables, stockDates and stockClosing, that I want to place in a queue.

IEnumerable<DateTime> stockDates = stocks.Select(equity => equity.Date);
IEnumerable<decimal> stockClosing = stocks.Select(equity => equity.Close);

// create a queue
Queue<MovingAverage> movingAverageQueue = new Queue<MovingAverage>();

How can I add stockDates and stockClosing into the newly created movingAverageQueue?

Here is the MovingAverage class:

namespace myBackEnd.Models
{
public class MovingAverage
{
    public DateTime Date { get; set; }
    public decimal Close { get; set; }

}
}

Upvotes: 1

Views: 200

Answers (3)

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34160

You can use IEnumerable.Zip() for this, however as the MovingAverage class is not shown in the post, I just used examplary properties:

movingAverageQueue = stockDates.Zip(stockClosing , (d, c) => new MovingAverage{ Date = d, Average = c});

If they are both in stocks and you want average of closing with a date then you can do this:

var result = stocks.GroupBy(x=> x.Date.Date)
             .Select(g => new MovingAverage{ Date = g.Key, Average = g.Average()});

Note that in stocks.GroupBy(x=> x.Date.Date) as x.Date is a DateTime, x.Date.Date will be its date (without time) so that all with the same date would be equal for grouping.

Upvotes: 1

Thowk
Thowk

Reputation: 407

You can use one of the Queue constructor Queue(ICollection)

new Queue<MovingAverage>(stocks.Select(stock => new MovingAverage(...))

Upvotes: 0

Jimi
Jimi

Reputation: 32248

If movingAverageQueue is an already existing Queue, if could just use ForEach on the Stocks [Enumerable] and .Enqueue() the values in a new MovingAverage object:

stocks.ForEach(s => movingAverageQueue.Enqueue(new MovingAverage { Date = s.Date, Close = s.Close }));

Upvotes: 0

Related Questions