我有一个带有股票报价信息的巨大字符串。它看起来像这样:
Date,Open,High,Low,Close,Volume,Adj Close
2016-05-06,49.919998,50.389999,49.66,50.389999,24715600,50.389999
2016-05-05,49.869999,50.299999,49.73,49.939999,25309500,49.939999
2016-05-04,49.84,50.060001,49.459999,49.869999,24171400,49.869999...........
如何将其打包成通用List<Stock>
:
Stock hs = new Stock();
hs.Date = Convert.ToDateTime();
hs.Open = Convert.ToDouble();
etc.
MyList.Add(hs)
答案 0 :(得分:2)
有以下假设,
,
分隔,您的输入是一个带有上述模式的长字符串。。您可以使用这些Linq
语句执行此操作。
string input = @"Date,Open,High,Low,Close,Volume,AdjClose,
2016-05-06,49.919998,50.389999,49.66,50.389999,24715600,50.389999,
2016-05-05,49.869999,50.299999,49.73,49.939999,25309500,49.939999,
2016-05-04,49.84,50.060001,49.459999,49.869999,24171400,49.869999";
var stacks = input.Split(new string[] {","}, StringSplitOptions.RemoveEmptyEntries)
.Select((x,i)=> new {index= i/7, item=x }) // split with 7 columns
.Where(x=>x.index !=0) // skip header row.
.GroupBy(x=>x.index)
.Select(x=> new Stack()
{
Date = DateTime.ParseExact(x.First().item.Trim(),"yyyy-MM-dd", CultureInfo.InvariantCulture),
Open = double.Parse(x.Skip(1).First().item),
High = double.Parse(x.Skip(2).First().item),
Low = double.Parse(x.Skip(3).First().item),
Close = double.Parse(x.Skip(4).First().item),
Volume = double.Parse(x.Skip(5).First().item),
AdjClose = double.Parse(x.Skip(6).First().item),
})
.ToList();
选中此Demo
答案 1 :(得分:0)
所以,我这样做了:
我的HisctoricalStock课程:
public class HistoricalStock
{
public DateTime Date { get; set; }
public double Open { get; set; }
public double High { get; set; }
public double Low { get; set; }
public double Close { get; set; }
public double Volume { get; set; }
public double AdjClose { get; set; }
}
我使用外部csv文件解决了我的问题(但它是可选的)。
List<HistoricalStock> retval = new List<HistoricalStock>();
try
{
File.WriteAllText("G:/Test.csv", web.DownloadString(string.Format("http://ichart.finance.yahoo.com/table.csv?s={0}&c={1}", ticker, yearToStartFrom)));
}
catch (FileNotFoundException exc)
{
Console.WriteLine(exc.Message);
}
StreamReader sr = new StreamReader("G:/Test.csv");
string currentLine;
List<string> stoksList = new List<string>();
// while stockList isn't empty
while ((currentLine = sr.ReadLine()) != null)
stoksList.Add(currentLine);
// First row is a header
stoksList.RemoveAt(0);
foreach (string str in stoksList)
{
string[] parsedString = str.Split(',');
HistoricalStock hs = new HistoricalStock();
hs.Date = Convert.ToDateTime(parsedString[0]);
hs.Open = Convert.ToDouble(parsedString[1]);
hs.High = Convert.ToDouble(parsedString[2]);
hs.Low = Convert.ToDouble(parsedString[3]);
hs.Close = Convert.ToDouble(parsedString[4]);
hs.Volume = Convert.ToDouble(parsedString[5]);
hs.AdjClose = Convert.ToDouble(parsedString[6]);
retval.Add(hs);
}