我正在尝试使用linq输出匹配数据的某个答案。这是代码,
public string[] netoilVar(string[] final)
{
var items = netOil.Zip(seqNum, (oil, seq) => new {Oil = oil, Seq = seq });
var items2 = netOil2.Zip(seqNum2, (oil, seq) => new { Oil = oil, Seq = seq });
List<string> vars = new List<string>();
foreach (var item in items2.Join(items, i => i.Seq, i => i.Seq, (a, b) => new
{
x = a.Seq,
y = this.GetTheAnswer(Convert.ToDouble(a.Oil), Convert.ToDouble(b.Oil)),
oilnum1 = a.Oil,
oilnum2 = b.Oil,
}))
{
vars.Add(item.y + "," + item.oilnum1 + "," + item.oilnum2);
final = vars.ToArray();
}
return final;
}
//BEGINS THE EXECUTE BUTTON METHOD
private void executeBtn_Click(object sender, EventArgs e)
{
//NET OIL VARIANCE MATHEMATICS
if (netOilRadBtn.Checked)
{
int i = listHead;
string[] x = new String[1000];
StreamWriter sw = new StreamWriter("testNetOil.csv");
sw.WriteLine("Lease Name, Field Name, Reservoir, Operator, County, ST, Majo, Resv Cat, Discount Rate, Net Oil Interest, Net Gas Interest, Working Interest, Gross Wells, Ultimate Oil, Ultimate Gas, Gross Oil, Gross NGL, Gross Gas, Net Oil, Net Gas, Net NGL, Revenue To Int., Oper. Expense, Total Invest., Revenue Oil, Revenue Gas, Operating Profit, Revenue NGL, Disc Net Income, SEQ, Well ID, INC ASN, Life Years, Net Oil Variance., Current Year's Net Oil, Last Year's Net Oil");
//Loops until the end of the list, printing out info
while (i != -1)
{
sw.WriteLine("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}, {13}, {14}, {15}, {16}, {17}, {18}, {19}, {20}, {21}, {22}, {23}, {24}, {25}, {26}, {27}, {28}, {29}, {30}, {31}, {32}, {33}, {34}",
QuoteString(leaseName[i]), fieldName[i], QuoteString2(reservoir[i]), operator1[i], county[i], state[i], majo[i], resvCatgory[i], disRate[i], netOil2Int[i], netGas2Int[i], workingInt[i], grossWells[i]
, ultOil[i], ultGas[i], grossOil[i], grossNGL[i], grossGas[i], netOil[i], netGas[i], netNGL[i], revToInt[i], operExpense[i], totInvest[i], revOil[i], revGas[i], operatingProfit[i],
revNGL[i], discNetIncome[i], seqNum[i], wellID[i], incASN[i], lifeYears[i], ownQual[i], netoilVar(x)[i]);
i = pointers[i];
}
sw.Close();
}
我在while循环上得到一个IndexOutOfRangeException,它打印出所有数据,特别是在netoilVar(x)[I]部分。有什么方法可以在那里得到正确的索引,所以我没有得到例外?
答案 0 :(得分:2)
虽然循环可能很危险,如您在此处所见。我强烈建议抽象出你的数据,以便更容易使用。
为您的数据建模如下:
public class MyData
{
public string LeaseName { get; set; }
public int UltOil { get; set; }
public int UltGas { get; set; }
public static string GetHeaders()
{
return "LeaseName, UltOil, UltGas";
}
public override string ToString()
{
return string.Join(",", LeaseName, UltOil, UltGas);
}
}
然后在写出你的csv文件时,使用这样的模型:
private void Foo()
{
//NET OIL VARIANCE MATHEMATICS
if (netOilRadBtn.Checked)
{
var input = new List<MyData>(); // <-- Fill in your data here.
StreamWriter sw = new StreamWriter("testNetOil.csv");
sw.WriteLine(MyData.GetHeaders());
//Loops until the end of the list, printing out info
foreach (var item in input)
{
sw.WriteLine(item);
}
sw.Close();
}
}
显然,这是缩写,您需要包含所有字段,名称并适当地键入它们。