I've got a list of time-related entites that are point-of-time-centric. E.g. each object PricesAtTimeX contains information about price of apples, price of banans for one specific point of time X.
Those I would like to transform to a JSON, more timeline-centric format using linq. E.g. an object BananaPrices that basically consists of a list of [date, value].
The concrete starting point PricesAtTimeX-class
public class PricesAtTimeX
{
public int ID { get; set; }
public DateTime Date { get; set; }
public int BananaPrice{ get; set; }
public int ApplePrice{ get; set; }
}
What I would love to make out of it:
[
{
"key": "BananaPrices",
"values": [[date1, bananaPrice1], [date2, bananaPrice2] ... ],
},
{
"key": "ApplePrices",
"values": [[date1, applePrice1], [date2, applePrice2] ... ],
}
]
My question is: How to get a list of (int, int) with Linq ?
My first attempt was to define a class that could be used to shell the data:
public class dataLine
{
public string key { get; set; }
// first tuple-int would be date converted to javascript datetime
public List<Tuple<int, int>> values { get; set; }
}
.. and then try to fill that with Linq:
var result = from x in db.Prices
select new List<dataLine>
{
new dataLine() {
key = "ApplePrices",
values = ???
}
};
return Json(result, JsonRequestBehavior.AllowGet);
Another approach would be to pack all values into separate Lists..
var xValues = from x in db.Prices select new List<DateTime>() { x.Date };
var yBananas = from x in db.Prices select new List<int>() { x.BananaPrice};
var yApples = from x in db.Prices select new List<int>() { x.ApplePrice};
.. and then use the .Zip-method to merge each of the Prices-Lists with the Date-List
public List<Tuple<int, int>> TupleMe(List<int> list1, List<int> list2)
{
return list1.Zip(list2, Tuple.Create).ToList();
}
I'd be thankful for any suggestions, hints or ideas!
public class ItemPrice { public string Desc{get;set;} public double Price{get;set;}}and then in yourPricesAtTimeXclass create apublic List<ItemPrice> Items{ get; set; }then simply do linq likevar banana = PricesAtTimeX.Items.Find(i=> i.Desc =="Banana");