Making var 's in a for-loop - c#

It is hard to explain but I will show an example of what I want in my code:
At the moment I do it this way:
var something1 = new (Microsoft.Office.Interop.Excel.Worksheet)appExcel.Worksheets.Add(Type.Missing, appExcel.Worksheets[appExcel.Worksheets.Count], 1, XlSheetType.xlWorksheet);
var something2 = new (Microsoft.Office.Interop.Excel.Worksheet)appExcel.Worksheets.Add(Type.Missing, appExcel.Worksheets[appExcel.Worksheets.Count], 1, XlSheetType.xlWorksheet);
var something3 = new (Microsoft.Office.Interop.Excel.Worksheet)appExcel.Worksheets.Add(Type.Missing, appExcel.Worksheets[appExcel.Worksheets.Count], 1, XlSheetType.xlWorksheet);
something1.Name = "sheet1";
something2.Name = "sheet2";
something3.Name = "sheet3";
I want to do the making of those var's in a for-loop
This is what I thought it should be:
for (int i=1;i<4;i++)
{
var ("something" +i) = new Microsoft.Office.Interop.Excel.Worksheet)appExcel.Worksheets.Add(Type.Missing, appExcel.Worksheets[appExcel.Worksheets.Count], 1, XlSheetType.xlWorksheet); // this (of course) doenst work
}
Any ideas on how to do this?
I tried this, but it didn't work:
var something = new (Microsoft.Office.Interop.Excel.Worksheet)appExcel.Worksheets.Add(Type.Missing, appExcel.Worksheets[appExcel.Worksheets.Count], 1 , XlSheetType.xlWorksheet)[4];

you can use a dictionary
var somethigs = new Dictionary<int, xxx.ApplicationClass>();
for (var i = 1; i < 4; i++)
{
somethigs[i] = new xxx.ApplicationClass();
}
//access them like this
somethigs[1].Name = "sheet1";
somethigs[2].Name = "sheet2";
or use an array like this
var somethigs = new xxx.ApplicationClass[4];
for (var i = 0; i < 4; i++)
{
somethigs[i] = new xxx.ApplicationClass();
}
somethigs[0].Name = "sheet1";
somethigs[1].Name = "sheet2";
keep in mind that arrays have zero based indexes.

If you know for sure, the amount of instances you will need, creating an array or list of class instances will do what you are after.
If you want something more sophisticated, you could also create a dictionary in which you provide names to each of your class instances, this could provide you with an access by name sort of thing mechanism.

Dictionary<string, ApplicationClass> dictionary = new Dictionary<string, ApplicationClass>();
for(int i = 0; i < 4; i++) {
dictionary.Add("something" + i, new xxx.ApplicationClass());
}
var myApplicationClass = dictionary["something1"];

You should use an array. In your particular case,
var something = new xxx.ApplicationClass[4];
for (int i = 0; i < 3; i++)
{
something[i] = new (Microsoft.Office.Interop.Excel.Worksheet)appExcel.Worksheets.Add(Type.Missing, appExcel.Worksheets[appExcel.Worksheets.Count], 1, XlSheetType.xlWorksheet);
something[i].Name = "sheet" + (i + 1).ToString();
}
You should probably look for more information about what arrays an how they work. See for example https://msdn.microsoft.com/en-us/library/aa288453%28v=vs.71%29.aspx

Related

NUnit Is.EqualTo treats different refenceres as equal

I'm copying an array like this:
var arrayOfMyTypes = new IMyType[1, 2]; //IMyType is an interface
arrayOfMyTypes[0, 0] = new MyType(); // that MyType implements
arrayOfMyTypes[0, 1] = new MyType();
var xRange = arrayOfMyTypes.GetLength(0);
var yRange = arrayOfMyTypes.GetLength(1);
var copy = new IMyType[xRange, yRange];
for (var xIdx = 0; xIdx < xRange; xIdx++)
{
for (var yIdx = 0; yIdx < yRange; yIdx++)
{
copy[xIdx, yIdx] = arrayOfMyTypes[xIdx, yIdx];
}
}
Assert.That(copy, Is.EqualTo(arrayOfMyTypes)); // true
Assert.That(copy, Is.Not.EqualTo(arrayOfMyTypes)); // false
To be clear, I want the elements be the same and the array a different one. So why are arrayOfMyTypes and copy considered equal by Nunit?
If you want to compare references rather than values, use Is.SameAs:
Assert.That(copy, Is.SameAs(arrayOfMyTypes)); // false

All permutations of form options

I'm trying to test a form by submitting a combination of all values to see if it breaks. These are ComboBoxes that I have stored in an ExtraField class
public class ExtraField
{
public String Name = ""; //name of form key
public Dictionary<String, String> Options = new Dictionary<String, String>(); //Format: OptionText, Value
}
I have generated a list of these fields
List<ExtraField> efList = new List<ExtraField>();
I was thinking all possible combinations of these fields could be added to a string list that I can parse (I was thinking name=opt|name=opt|name=opt). I've provided an example of what would work below (where ExtraField list Count==3):
List<ExtraField> efList = new List<ExtraField>();
ExtraField f1 = new ExtraField();
f1.Name = "name1";
f1.Options.Add("text", "option1");
f1.Options.Add("text2", "option2");
f1.Options.Add("text3", "option3");
efList.Add(f1);
ExtraField f2 = new ExtraField();
f2.Name = "name2";
f2.Options.Add("text", "option1");
f2.Options.Add("text2", "option2");
f2.Options.Add("text3", "option3");
f2.Options.Add("text4", "option4");
efList.Add(f2);
ExtraField f3 = new ExtraField();
f3.Name = "name3";
f3.Options.Add("text2", "option1");
f3.Options.Add("text3", "option2");
f3.Options.Add("text4", "option3");
f3.Options.Add("text5", "option4");
f3.Options.Add("text6", "option5");
efList.Add(f3);
Should produce
name1=option1|name2=option1|name3=option1
name1=option1|name2=option1|name3=option2
name1=option1|name2=option1|name3=option3
name1=option1|name2=option1|name3=option4
name1=option1|name2=option1|name3=option5
name1=option1|name2=option2|name3=option1
name1=option1|name2=option2|name3=option2
name1=option1|name2=option2|name3=option3
name1=option1|name2=option2|name3=option4
name1=option1|name2=option2|name3=option5
name1=option1|name2=option3|name3=option1
name1=option1|name2=option3|name3=option2
name1=option1|name2=option3|name3=option3
name1=option1|name2=option3|name3=option4
name1=option1|name2=option3|name3=option5
name1=option1|name2=option4|name3=option1
name1=option1|name2=option4|name3=option2
name1=option1|name2=option4|name3=option3
name1=option1|name2=option4|name3=option4
name1=option1|name2=option4|name3=option5
name1=option2|name2=option1|name3=option1
...etc
All ExtraFields in the list need to have a value and I need all permutations in one format or another. It's a big list with a lot of permutations otherwise I'd do it by hand.
Well I did it... But I'm not proud of it. I'm sure there is a better way of doing it recursively. Hopefully this helps someone.
public List<String> GetFormPermutations(List<ExtraField> inList)
{
List<String> retList = new List<String>();
int[] listIndexes = new int[inList.Count];
for (int i = 0; i < listIndexes.Length; i++)
listIndexes[i] = 0;
while (listIndexes[inList.Count-1] < inList.ElementAt(inList.Count-1).Options.Count)
{
String cString = "";
//after this loop is complete. a line is done.
for (int i = 0; i < inList.Count; i++) {
String key = inList.ElementAt(i).Name;
Dictionary<String, String> cOptions = inList.ElementAt(i).Options;
String value = cOptions.ElementAt(listIndexes[i]).Value;
cString += key + "=" + value;
if (i < inList.Count - 1)
cString += "|";
}
retList.Add(cString);
listIndexes[0]++;
for(int i = 0; i < inList.Count -1; i++)
{
if (listIndexes[i] >= inList.ElementAt(i).Options.Count)
{
listIndexes[i] = 0;
listIndexes[i + 1]++;
}
}
}
return retList;
}
UPDATED ANSWER
So I managed to do it recursively. I haven't done this since college :D
Here's the whole class:
https://gist.github.com/Rastamas/8070ae7e1471d2183451a17bcf061376
PREVIOUS ANSWER BELOW
This goes through your list and adds the strings to a StringBuilder in the format you showed
foreach (var item in efList)
{
foreach (var option in item.Options)
{
stringBuilder.Append(String.Format("{0}={1}|", item.Name, option.Value));
}
stringBuilder.Remove(stringBuilder.Length - 1, 1);
stringBuilder.AppendLine();
}
Then you can just use stringBuilder.ToString() to get the whole list.

how to add new object for each item in the list

I have assigned data to a list like below.
foreach (var items in niledetails)
{
cruiseDetails.Add(new CruiseDetails()
{
mainID = items.cruiseID,
idL = items.idlength,
mainimageUrl = items.cruiseimageUrl,
adultPrice = items.adultprice,
location = items.cruiseLocation,
numberofDays = items.numberofdays,
description = items.description,
embarkationP = items.embarkationport,
cruiseTyp = items.cruisetype,
childPrice = items.childprice,
totalPrice = items.totalprice,
farecode = items.referenceNumber,
experience = items.cruiseName,
fullcategoryname = items.cruiseCabname
});
}
this works fine.this has 30 objects and for each object has 14 key/values.now what I want is to add additional value for each object in the list.
that means something like this
for(int i=0;i<cruiseDetails.Count();i++)
{
//for each object I want to add another key value( 15th) for all 30 objects.
}
How can I do that. hope your help.
NOTE : I'm not looking for this. EX:
cruiseDetails.Insert(0, new someModel() { city = "All"});
for(int i=0;i<cruiseDetails.Count();i++)
{
cruiseDetails[i].additionalKey = val;
}
try this code
Try this:
foreach (CruiseDetails myCruiseDetail in cruiseDetails){
myCruiseDetail.myNewKey = myNewValue;
}
try something as this:
List<Tuple<int, CruiseDetails>> list = new List<Tuple<int, CruiseDetails>>();
CruiseDetails> sourceCruises = new List<CruiseDetails>();
int i = 0;
foreach (var c in sourceCruises)
{
list.Add(new Tuple<int, CruiseDetails>(i, c));
i++;
}
Set your properties in your loop
for(int i=0;i<cruiseDetails.Count();i++)
{
cruiseDetails[i].mynewproperty = somevalue;
}

Got NullReferenceException When I use same code but different expression

I'm writing a project about game's character data.
And each character in the data document have four types, Lv1 and LvMAX, and HP, STR, VIT, INT, MEN.
I use top one code at the middle part and got NullReferenceException when I use it to get some data like:
int x = CD.Parameters.Basic.Awaked.Force.Lv1.STR;
Force will be null. But when I use buttom one at the middle part, Force won't be null.
What's the difference between that two?
Code below
public class ParamType
{
public ParamLv Mebius, Force, Aegis, Magius;
string cost;
DataRow[] Datas;
List<int> ToMebius = new List<int>(), ToForce = new List<int>(), ToAegis = new List<int>(), ToMagius = new List<int>(); //HP, HP, STR, STR, VIT, VIT, INT, INT, MEN, MEN
public ParamType(SData Data, bool awaked)
{
if (awaked)
{
Data.CharaID = CharaCOM.AwakedID(Data.CharaID);
}
Datas = DataCOM.Search(Data.CharaID, Data.DTs.Source, Data.TitleP.Start[(int)DataTitle.CharacterParams], Const.COL_CHARACTER_ID, Const.COL_CHARACTER_ID);
cost = DataCOM.Search(Data.DTs.Source, Data.CharaID, Const.COL_COST, 0, Data.TitleP.Start[(int)DataTitle.CharacterParams], Const.COL_CHARACTER_ID_WITH_TYPE);
List<int>[] SArray = { ToMebius, ToForce, ToAegis, ToMagius };
for (int i = 0; i < Datas.Length; i++)
{
SArray[i] = new List<int>();
for (int j = Const.COL_PARAM_MIN; j < Const.COL_PARAM_MIN + Const.COL_PARAM_LENGTH; j++)
{
SArray[i].Add(Convert.ToInt32(Datas[i][j]));
}
}
/*
this will send NullReference Exception
ParamLv[] PLArray = new ParamLv[4];
for (int i = 0; i < SArray.Length; i++)
{
PLArray[i] = new ParamLv(Data, SArray[i]);
}
*/
/*
This won't get exception and I can get correct data I want.
Mebius = new ParamLv(Data, SArray[0]);
Force = new ParamLv(Data, SArray[1]);
Aegis = new ParamLv(Data, SArray[2]);
Magius = new ParamLv(Data, SArray[3]);
*/
}
public class ParamLv
{
public Params Lv1, LvMax;
List<int> ToLv1 = new List<int>(), ToLvMAX = new List<int>(); //HP, STR, VIT, INT, MEN
public ParamLv(SData Data, List<int> ParamsL)
{
for (int i = 0; i < ParamsL.Count; i += Const.COL_PARAM_MIN_MAX_GAP)
{
ToLv1.Add(ParamsL[i]);
ToLvMAX.Add(ParamsL[i + 1]);
}
Lv1 = new Params(Data, ToLv1);
LvMax = new Params(Data, ToLvMAX);
}
public class Params
{
//some method and properties to get or set Parameters.
}
}
Please tell me if something still bad, and this is my first time to ask question here, so If I did something wrong, please tell me. Thanks for #MicroVirus , #Moriarty and #mvikhona told my mistake.
Mebius = new ParamLv(Data, SArray[0]);
Force = new ParamLv(Data, SArray[1]);
Aegis = new ParamLv(Data, SArray[2]);
Magius = new ParamLv(Data, SArray[3]);
This works, because you are assigning reference to new ParamLv to your properties.
But in this case:
ParamLv[] PLArray = { Mebius, Force, Aegis, Magius };
for (int i = 0; i < PLArray.Length; i++)
{
PLArray[i] = new ParamLv(Data, SArray[i]);
}
you aren't filling your array with variables/properties themselves, but you are filling it with references your properties hold, in the end your array will hold reference to 4 new ParamLw, but your property Force will stay null.
Edit:
I'll try to explain it a bit different. Let's say you have this code:
ParamLv[] PLArray = { Force };
At this moment value of PLArray[0] is same as value of Force, but PLArray[0] isn't Force.
The moment you do this:
PLArray[0] = new ParamLv(Data, null);
new ParamLv(Data, null) returns reference to new ParamLv and you assign this to your PLArray[0], but like I said before PLArray[0] isn't Force, so Force will stay unchanged.
If that didn't explain it well, try to look at this piece of code, it does what you are trying to do.
int a = 1;
int[] myArr = { a }; // a = 1, myArr[0] = 1
myArr[0] = 2; // a = 1, myArr[0] = 2
object obj = null;
object[] objArr = { obj }; // obj = null, objArr[0] = null
objArr[0] = new object(); // obj = null, objArr[0] = 'reference to new object'

To create a list with multiple list inside it

Below is my main list
var serie_line = new { name = series_name, data = new List<object>() };
here I add items in data as follows,
serie_line.data.Add(child_object_name);
serie_line.data.Add(period_final_value );
I then add this var serie_line to another list series as follows,
List<object> series = new List<object>();
series.Add(serie_line);
finally ,I serialize this series into JSON as below,
var obj4 = new { legend = legend, title,chart, series};
JSON_File_Returned = jSearializer.Serialize(obj4);
whereas
System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer();
Now Output I am getting is as follows,
{
"legend":{"enabled":"true"},
"title":{"text":"Financial"},
"chart":{"type":"pie"},
"series":[
{"name":"Actual","data":["Market Share",20.00]},
{"name":"Actual","data":["Sales Growth",30.00]},
{"name":"Actual","data":["Operating Profit",40.00]},
{"name":"Actual","data":["Gross Margin %",10.00]}
]
}
But my required output is as follows,
{
"legend":{"enabled":"true"},
"title":{"text":"Financial"},
"chart":{"type":"pie"},
"series":[
{"name":"Actual","data":[["Market Share",20.00],["Sales Growth",30.00],["Operating Profit",40.00],["Gross Margin %",10.00]]}
]
}
So..That I can plot pie chart in highchart using this JSON output...I have tried for everything like using dictionary,making different class and then using it's object and so on...but can't make it out....
Below is my entire code...if in case I am messing with any loop and I don't recognize it but any one might notice it..please check the below code for the same..
var serie_line = new { name = series_name, data = new List<object>() };
for (int k = 0; k <= read_Series_Splitted_Name.Length; k++) //for loop for passing chart type in series
{
for (int i = 0; i < id_series_before_offset.Count; i++) //for loop for counting series ID
{
var xmlAttributeCollection = id_series_before_offset[i].Attributes;
if (xmlAttributeCollection != null)
{
var seriesid = xmlAttributeCollection["id"];
xmlActions_id[i] = seriesid.Value;
resulted_series_id = seriesid.Value;
series_name = Client.GetAttributeAsString(sessionId, resulted_series_id, "name", "");
new_series_name = series_name;
series_Atribute = Client.GetAttributeAsString(sessionId, resulted_series_id, "symbol", "");
if (read_Series_Splitted_Name_store == series_Atribute)
{
serie_line = new { name = series_name, data = new List<object>() };
}
k++;
// Forloop for PeriodId and It's Value
var value = Read_XML_Before_Offset.SelectNodes("//measure.values/series[" + (i + 1) + "]/value");
var xmlActions = new string[value.Count];// for periodname
var xmlActionsone = new string[value.Count]; // for period value
for (int j = 0; j < value.Count; j++)
{
var xmlAttributeCollection_for_period = value[j].Attributes;
if (xmlAttributeCollection_for_period != null)
{
if (i == 0 && a == 0)
{
var periodid = xmlAttributeCollection_for_period["periodid"];
xmlActions[j] = periodid.Value;
period_final_id = periodid.Value;
period_name = Client.GetAttributeAsString(sessionId, periodid.Value, "name", "");
period_Name.Add(period_name);
}
try
{
var action = xmlAttributeCollection_for_period["value"]; // xmlActionsone[j] = action.Value;
period_final_value = float.Parse(action.Value);
// serie_line.data.Add(period_final_value);
serie_line.data.Add(child_object_name);
serie_line.data.Add(period_final_value );
}
catch (Exception ex1)
{
serie_line.data.Add("");
serie_line.data.Add( null );
}
}
}
}
}
}
series.Add(serie_line);
Your C# code should look something like this all stripped down:
var serie_line = new { name = "Actual", data = new List<object>() };
serie_line.data.Add(new List<object>() {"Market Share", 20.0});
serie_line.data.Add(new List<object>() {"Sales Growth", 30.0});
serie_line.data.Add(new List<object>() {"Operting Profit", 40.0});
serie_line.data.Add(new List<object>() {"Gross Margin %", 10.0});
jSearializer.Serialize(serie_line);
Which produces:
{"name":"Actual","data":[["Market Share",20],["Sales Growth",30],["Operting Profit",40],["Gross Margin %",10]]}
I'm not following the bottom part of the code (how you create child_object_name and period_final_value, but I think you want:
serie_line.data.Add(new List<object>() {child_object_name, period_final_value });
Instead of:
serie_line.data.Add(child_object_name);
serie_line.data.Add(period_final_value );

Categories