To create a list with multiple list inside it - c#

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 );

Related

CSharp Generate polygons from a set of intersecting lines

https://gis.stackexchange.com/questions/58245/generate-polygons-from-a-set-of-intersecting-lines
https://i.stack.imgur.com/UUyHF.png
https://i.stack.imgur.com/3ClRI.png
I want to find the bounding polygon like this link.
I'm using C# nettopologysuite like the jts library shown in this link, but the polygon I want doesn't come out.
How can I extract polygons?
Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
PromptEntityOptions pEntOpt1 = new PromptEntityOptions("Outter Boundary");
pEntOpt1.SetRejectMessage("is Not Polyline");
pEntOpt1.AddAllowedClass(typeof(Polyline), true);
PromptEntityResult pEntRes1 = ed.GetEntity(pEntOpt1);
string typeName = RXObject.GetClass(typeof(Polyline)).DxfName;
TypedValue[] tv = new TypedValue[1] { new TypedValue((int)DxfCode.Start, typeName) };
SelectionFilter sf = new SelectionFilter(tv);
PromptSelectionResult pSelectRes = ed.GetSelection(sf);
if (pSelectRes.Status != PromptStatus.OK)
return;
ObjectId boudaryPlineId = pEntRes1.ObjectId;
ObjectId[] innerPlineids = pSelectRes.Value.GetObjectIds();
ObjectIdCollection innerBoundaries = new ObjectIdCollection(innerPlineids);
try
{
using (doc.LockDocument())
{
using (Transaction tr = db.TransactionManager.StartTransaction())
{
Polygonizer polygonizer = new Polygonizer();
GeometryFactory gf = new GeometryFactory();
Polyline boundaryPline = tr.GetObject(boudaryPlineId, OpenMode.ForWrite) as Polyline;
Coordinate[] coords = new Coordinate[boundaryPline.NumberOfVertices + 1];
for (int j = 0; j < boundaryPline.NumberOfVertices; j++)
{
Point3d pos = boundaryPline.GetPoint3dAt(j);
coords[j] = new Coordinate(pos.X, pos.Y);
}
coords[boundaryPline.NumberOfVertices] = new Coordinate(boundaryPline.StartPoint.X, boundaryPline.StartPoint.Y);
Polygon pg = gf.CreatePolygon(coords);
List<Geometry> plines = new List<Geometry>();
foreach (ObjectId indexid in innerBoundaries)
{
Polyline indexPline = tr.GetObject(indexid, OpenMode.ForWrite) as Polyline;
Coordinate[] coords2 = new Coordinate[indexPline.NumberOfVertices];
for (int i = 0; i < indexPline.NumberOfVertices; i++)
{
Point3d pos = indexPline.GetPoint3dAt(i);
coords2[i] = new Coordinate(pos.X, pos.Y);
}
LineString ls1 = new LineString(coords2);
polygonizer.Add(ls1);
}
ICollection<Geometry> test = polygonizer.GetPolygons();
foreach (Geometry polygon in test)
{
// to do
}
tr.Commit();
}
}
}
catch
{
}
outter Boundary
inner Boundary
The Red Polygon I want to find
This is my second question in English, so please understand the lack of expression.
-------------- After applying the answer below --------------
private List<NetGeometry> GetPolygons(Transaction tr, List<LineString> lineStrings)
{
List<NetGeometry> polygons = new List<NetGeometry>();
Polygonizer polygonizer = new Polygonizer(false);
GeometryFactory gf = new GeometryFactory(new PrecisionModel(10000));
var noder = new SnapRoundingNoder(new PrecisionModel(10000)); // adjust PrecisionModel to your needs, must be fixed.
noder.ComputeNodes(lineStrings.Select(s => (ISegmentString)new NodedSegmentString(s.Coordinates, s)).ToList());
var noded = noder.GetNodedSubstrings();
polygonizer.Add(noded.Select(n => (Geometry)gf.CreateLineString(n.Coordinates)).ToList());
//for ( int i = 0; i < lineStrings.Count; i++)
//{
// polygonizer.Add(lineStrings[i]);
//}
ICollection<NetGeometry> result = polygonizer.GetPolygons();
foreach (NetGeometry index in result)
{
if ( index is Polygon pg)
{
polygons.Add(pg);
}
}
return polygons;
}
Results after application
All input geometries to Polygonizer should be LineStrings.
The whole input set of LineStrings must be fully noded:
var noder = new SnapRoundingNoder(new PrecisionModel(1000)); // adjust PrecisionModel to your needs, must be fixed.
noder.ComputeNodes(lines.Select(s => (ISegmentString)new NodedSegmentString(s.Coordinates, s)).ToList());
var noded = noder.GetNodedSubstrings();
polygonizer.Add(noded.Select(n => (Geometry)gf.CreateLineString(n.Coordinates)).ToList());

Google Reporting API V4 Missing Values

I've been having a problem with Google's analytic reporting api v4. When I make a request, i can get data back, but some dimension and metric values are missing and/or inconsistent.
For example if i wanted the fullRefferer, it would return (not set). Or when i do get values my page views value could be 1312 and my sessions could be 26.
My code for making the request is below:
public GetReportsResponse Get(string viewId, DateTime startDate, DateTime endDate, string nextPageToken = null)
{
try
{
var credential = GetCredential();
using (var svc = new AnalyticsReportingService(
new BaseClientService.Initializer
{
HttpClientInitializer = credential
}))
{
var mets = new List<Metric>
{
new Metric
{
Alias = "Users",
Expression = "ga:users"
},
new Metric
{
Alias = "Bounce Rate",
Expression = "ga:bounceRate"
},
new Metric
{
Alias = "Page Views",
Expression = "ga:pageViews"
},
new Metric()
{
Alias = "Sessions",
Expression = "ga:sessions"
}
};
var dims = new List<Dimension>
{
new Dimension { Name = "ga:date" },
new Dimension { Name = "ga:hour" },
new Dimension { Name = "ga:browser" },
new Dimension { Name = "ga:pagePath" },
new Dimension { Name = "ga:fullReferrer"}
};
var dateRange = new DateRange
{
StartDate = startDate.ToFormattedString(),
EndDate = endDate.ToFormattedString()
};
var reportRequest = new ReportRequest
{
DateRanges = new List<DateRange> { dateRange },
Dimensions = dims,
Metrics = mets,
ViewId = viewId,
PageToken = nextPageToken
};
var getReportsRequest = new GetReportsRequest
{
ReportRequests = new List<ReportRequest> { reportRequest },
};
var batchRequest = svc.Reports.BatchGet(getReportsRequest);
var response = batchRequest.Execute();
return response;
}
}
catch (Exception e)
{
return null;
}
}
And my code for filtering the results is here:
public static List<AnalyticEntry> Filter(Google.Apis.AnalyticsReporting.v4.Data.GetReportsResponse response)
{
if (response == null) return new List<AnalyticEntry>();
List<GoogleDataDto> gData = new List<GoogleDataDto>();
foreach (var report in response.Reports)
{
foreach (var row in report.Data.Rows)
{
GoogleDataDto dto = new GoogleDataDto();
foreach (var metric in row.Metrics)
{
foreach (var value in metric.Values)
{
int index = metric.Values.IndexOf(value);
var metricHeader = report.ColumnHeader.MetricHeader.MetricHeaderEntries[index];
switch (metricHeader.Name)
{
case "Sessions":
dto.Sessions = Convert.ToInt32(value);
break;
case "Bounce Rate":
dto.BounceRate = Convert.ToDecimal(value);
break;
case "Page Views":
dto.PageViews = Convert.ToInt32(value);
break;
case "Users":
dto.Users = Convert.ToInt32(value);
break;
}
}
}
foreach (var dimension in row.Dimensions)
{
int index = row.Dimensions.IndexOf(dimension);
var dimensionName = report.ColumnHeader.Dimensions[index];
switch (dimensionName)
{
case "ga:date":
dto.Date = dimension;
break;
case "ga:hour":
dto.Hour = dimension;
break;
case "ga:browser":
dto.Browser = dimension;
break;
case "ga:pagePath":
dto.PagePath = dimension;
break;
case "ga:source":
dto.Source = dimension;
break;
case "ga:fullRefferer":
dto.Referrer = dimension;
break;
}
}
gData.Add(dto);
}
}
return Combine(gData);
}
private static List<AnalyticEntry> Combine(IReadOnlyCollection<GoogleDataDto> gData)
{
List<AnalyticEntry> outputDtos = new List<AnalyticEntry>();
var dates = gData.GroupBy(d => d.Date.Substring(0,6)).Select(d => d.First()).Select(d => d.Date.Substring(0,6)).ToList();
foreach (var date in dates)
{
var entities = gData.Where(d => d.Date.Contains(date)).ToList();
AnalyticEntry dto = new AnalyticEntry
{
Date = date.ToDate(),
PageViews = 0,
Sessions = 0,
Users = 0,
BounceRate = 0
};
foreach (var entity in entities)
{
dto.BounceRate += entity.BounceRate;
dto.PageViews += entity.PageViews;
dto.Users += entity.Users;
dto.Sessions += entity.Sessions;
}
dto.BounceRate = dto.BounceRate / entities.Count();
var dictionaries = entities.GetDictionaries();
var commonBrowsers = dictionaries[0].GetMostCommon();
var commonTimes = dictionaries[1].GetMostCommon();
var commonPages = dictionaries[2].GetMostCommon();
var commonSources = dictionaries[3].GetMostCommon();
var commonReferrers = dictionaries[4].GetMostCommon();
dto.CommonBrowser = commonBrowsers.Key;
dto.CommonBrowserViews = commonBrowsers.Value;
dto.CommonTimeOfDay = commonTimes.Key.ToInt();
dto.CommonTimeOfDayViews = commonTimes.Value;
dto.CommonPage = commonPages.Key;
dto.CommonPageViews = commonPages.Value;
dto.CommonSource = commonSources.Key;
dto.CommonSourceViews = commonSources.Value;
dto.CommonReferrer = commonReferrers.Key;
dto.CommonReferrerViews = commonReferrers.Value;
outputDtos.Add(dto);
}
return outputDtos;
}
I'm not sure what else to put, please comment for more info :)
Solved!
Originally I was trying to find a 'metric name' based on the location of a value in an array. So using the location I would get the name and set the value.
The problem was the array could have multiple values which were the same.
For example:
var arr = [1,0,3,1,1];
If a value was 1, I was trying to use the location of 1 in the array to get a name.
So if the index of 1 in the array was 0, I would find its name by using that index and finding the name in another array.
For example:
var names = ['a','b','c'];
var values = [1,2,1];
var value = 1;
var index = values.indexOf(value); // which would be 0
SetProperty(
propertyName:names[index], // being a
value: value);
Although its hard to explain I was setting the same value multiple times due to the fact that there were more than one value equal to the same thing in the array.
Here is the answer. Tested and works
public List<GoogleDataDto> Filter(GetReportsResponse response)
{
if (response == null) return null;
List<GoogleDataDto> gData = new List<GoogleDataDto>();
foreach (var report in response.Reports)
{
foreach (var row in report.Data.Rows)
{
GoogleDataDto dto = new GoogleDataDto();
foreach (var metric in row.Metrics)
{
int index = 0; // Index counter, used to get the metric name
foreach (var value in metric.Values)
{
var metricHeader = report.ColumnHeader.MetricHeader.MetricHeaderEntries[index];
//Sets property value based on the metric name
dto.SetMetricValue(metricHeader.Name, value);
index++;
}
}
int dIndex = 0; // Used to get dimension name
foreach (var dimension in row.Dimensions)
{
var dimensionName = report.ColumnHeader.Dimensions[dIndex];
//Sets property value based on dimension name
dto.SetDimensionValue(dimensionName, dimension);
dIndex++;
}
// Will only add the dto to the list if its not a duplicate
if (!gData.IsDuplicate(dto))
gData.Add(dto);
}
}
return gData;
}

Filter products with ElasticSearch concat a lot of filter

I've been trying to filter products with Elasticsearch for a few hours, unfortunately to no avail.
I need to find products that belong to certain categories and at the same time have selected several brands and one size.
Help :(
json screen
querycontainer build method
private QueryContainer CreateOrQueryFromFilter(QueryContainer queryContainer, SortedSet<string> filter, string fieldName)
{
if (filter != null && filter.Count > 0)
{
foreach (var item in filter)
{
queryContainer |= new TermQuery()
{
Name = fieldName + "named_query",
Boost = 1.1,
Field = fieldName,
Value = item
};
}
}
return queryContainer;
}
and search method
public ResultModel SearchRequest(RequestModel r)
{
string key = string.Format("search-{0}-{1}", r.CacheKey + "-" + ProductCatalog.Model.Extension.StringHelper.UrlFriendly(r.SearchText), r.Prefix);
node = new Uri("http://xxxx:9200/");
settings = new ConnectionSettings(node);
settings.DisableDirectStreaming();
settings.DefaultIndex("products");
client = new ElasticClient(settings);
// return AppCache.Get(key, () =>
// {
DateTime start = DateTime.Now;
ResultModel result = new ResultModel(r.Canonical, r.RouteObject);
if (!string.IsNullOrEmpty(r.Prefix))
{
result.Prefix = r.Prefix;
}
QueryContainer c = new QueryContainer();
if (r.CategoryFilterChilds != null && r.CategoryFilterChilds.Count > 0)
{
var a1 = new SortedSet<string>(r.CategoryFilterChilds.Select(a => (string)a.ToString()));
c = CreateOrQueryFromFilter(c, a1, "categories");
}
else
{
if (r.CategoryFilterRoots != null && r.CategoryFilterRoots.Count > 0)
{
var a1 = new SortedSet<string>(r.CategoryFilterRoots.Select(a => (string)a.ToString()));
c = CreateOrQueryFromFilter(c, a1, "categories");
}
else
{
// null
}
}
var filters = new AggregationDictionary();
if (r.IsBrandFilter)
{
c = CreateOrQueryFromFilter(c, r.SelectedBrands, "brands");
}
if (r.IsColorFilter)
{
c = CreateOrQueryFromFilter(c, r.SelectedBrands, "colors");
}
int skip = (r.Page * r.PageSize) - r.PageSize;
ISearchRequest r2 = new SearchRequest("products");
r2.From = 1;
r2.Size = r.PageSize;
r2.Query = c;
string[] Fields = new[] { "brands", "shopId" };
AggregationBase aggregations = null;
foreach (string sField in Fields)
{
var termsAggregation = new TermsAggregation("agg_" + sField)
{
Field = sField,
Size = 120,
Order = new List<TermsOrder> { TermsOrder.TermDescending }
};
if (aggregations == null)
{
aggregations = termsAggregation;
}
else
{
aggregations &= termsAggregation;
}
}
r2.Aggregations = aggregations;
var c2 = client.Search<ShopProductElastic>(r2);
var ShopsBuf = (Nest.BucketAggregate)(c2.Aggregations["agg_brands"]);
var ShopsCount = ShopsBuf.Items.Count();
var results = c2;
result.BrandsRequest = new SortedDictionary<string, int>();
foreach (Nest.KeyedBucket<object> item in ShopsBuf.Items)
{
result.BrandsRequest.Add((string)item.Key, (int)(item.DocCount ?? 0));
}
result.CategorySelected = r.CategoryCurrent;
result.TotalCount = 10;
var costam = results.Documents.ToList();
var targetInstance = Mapper.Map<List<Products>>(costam);
result.Products = targetInstance;
result.Page = r.Page;
result.PageSize = r.PageSize;
result.IsBrandFilter = r.IsBrandFilter;
result.IsColorFilter = r.IsColorFilter;
result.IsPatternFilter = r.IsPatternFilter;
result.IsSeasonFilter = r.IsSeasonFilter;
result.IsShopFilter = r.IsShopFilter;
result.IsSizeFilter = r.IsSizeFilter;
result.IsStyleFilter = r.IsStyleFilter;
result.IsTextileFilter = r.IsTextileFilter;
DateTime stop = DateTime.Now;
result.SearchTime = stop - start;
result.SearchText = r.SearchText;
return result;
// }, TimeSpan.FromHours(8));
}
I have all products that have a given brand or categories. However, i need all products of a selected brand in selected categories

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'

Making var 's in a for-loop

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

Categories