I have a very unique situation in which i am generating a file for which i have to use nested loops.
So for the current file i have 4 level of nested foreach (). when the data is less its performance is ok ok type still not good but when data start growing the loop grows exponentially due to nested.
Hence it is taking lot of time. Please suggest me some alternative or how can i optimize my code.
Use case:
The file i am trying to print say is having a blue print of the structure which have these nested loop, so i had to go with nesting .
Eg:
Member Details (Level 1)
Health Coverage (Level 2)
Provider Information (Level 3)
BeneFits (Level 4)
So Member details which can have multiple Health Coverage in which each health Coverage can have multiple Provider in which each Provider can have multiple benefits.
hope this help with my situation in a real time example
Level1
foreach()
{
//do some stuff
//writer.writeline();
level2
foreach()
{
//do some stuff
//writer.writeline();
level3
foreach()
{
//do some stuff
//writer.writeline();
level4
foreach()
{
//do some stuff
//writer.writeline();
}
}
}
}
Code
In the method used below writeWholeLine() , it again contain 3 nested for each loop, was not able to post the code here due to limit of character of body
private string TransactionsGeneration(StreamWriter writer, string line, int maximumCount)
{
#region Re-Generation
TransactionCounter = 0;
foreach (DataRow memRow in MemberTblMaster.Rows)
{
TransactionCounter++;
line = string.Empty; //begin of a new Transaction
//Counter
TotalLines = 0;
ST_SE_UniqueCode = 0;
// Fill the dataset based on the member id
MemberID = Convert.ToString(memRow[MEMBER_ID]).Trim();
HealthCoverageTbl = HealthCoverageTblMaster.AsEnumerable().Where(x => x.Field<string>(MEMBER_ID).Trim() == MemberID);
Associations834Tbl = Associations834TblMaster.AsEnumerable().Where(x => x.Field<string>(MEMBER_ID).Trim() == MemberID);
AddressTbl = AddressTblMaster.AsEnumerable().Where(x => x.Field<string>(MEMBER_ID).Trim() == MemberID);
GenNameInfoTbl = GenNameInfoTblMaster.AsEnumerable().Where(x => x.Field<string>(Gen_Name_ID).Trim() == memRow[Sponsor_ID].ToString().Trim() ||
x.Field<string>(Gen_Name_ID).Trim() == memRow[Payer_ID].ToString().Trim() ||
x.Field<string>(Gen_Name_ID).Trim() == memRow[TPA_Broker_ID].ToString().Trim()
);
ContactTbl = ContactTblMaster.AsEnumerable().Where(x => x.Field<string>(MEMBER_ID).Trim() == MemberID);
GenReferenceTbl = GenReferenceTblMaster.AsEnumerable().Where(x => x.Field<string>(MEMBER_ID).Trim() == MemberID);
MemberTbl = MemberTblMaster.AsEnumerable().Where(x => x.Field<string>(MEMBER_ID).Trim() == MemberID);
// Based on Health Coverage
//Provider , COB
var loopLevel1 = (from row in LoopOrder.AsEnumerable()
where row.Field<int>(HIERARCHY_LEVEL) == 1
&& !Header.Contains(row.Field<string>(LOOP_ID).Trim())
&& !Footer.Contains(row.Field<string>(LOOP_ID).Trim())
select row);
foreach (DataRow parentLoop in loopLevel1)
{
//Level 1
//TODO : Need to implement the parent loop functionality
ParentLoop = Convert.ToString(parentLoop[PARENT_LOOP]);
string loopIDofLoopOrder = parentLoop[LOOP_ID].ToString();
LoopID = loopIDofLoopOrder;
var resultLevel1 = (from row in ValidationElementAttribute.AsEnumerable()
where row.Field<string>(LoopIdSegment).Trim() == loopIDofLoopOrder
select row);
if (resultLevel1.Any())
{
int maxCount1;
if (String.IsNullOrEmpty(Convert.ToString(parentLoop[Repeat_max])))
maxCount1 = maximumCount; //Max_Repitition = NULL means infinite number of repititions allowed; no upper cap
else
maxCount1 = Convert.ToInt32(parentLoop[Repeat_max]);
for (int i = 0; i < maxCount1; i++) //until all the repititions are covered, keep repeating the same loop, else change the parent loop
{
SkipLine = false;
WriteWholeLine(line, i, resultLevel1, writer, memRow);
#region Level 2
var loopLevel2 = (from row in LoopOrder.AsEnumerable()
where row.Field<int>(HIERARCHY_LEVEL) == 2
&& row.Field<string>(PARENT_LOOP).Trim() == loopIDofLoopOrder.Trim()
select row);
foreach (DataRow level2 in loopLevel2)
{
//Level 2
// ChildLoop = Convert.ToString(level2["PARENT_LOOP"]);// 1000C
ChildLoop = Convert.ToString(level2[LOOP_ID]);// 1100C
LoopID = ChildLoop;
var resultLevel2 = (from row in ValidationElementAttribute.AsEnumerable()
where row.Field<string>(LoopIdSegment).Trim() == ChildLoop.Trim()
select row);
//var healthCoverageIdList = memberEnrollment.Select(x => x.Field<object>(Health_Coverage_ID)).Distinct().ToList();
if (resultLevel2.Any())
{
int maxCount2;
if (String.IsNullOrEmpty(Convert.ToString(level2[Repeat_max])))
maxCount2 = maximumCount;
else
maxCount2 = Convert.ToInt32(level2[Repeat_max]);
//Custom Code
// maxCount2= ChildLoop == _2300 ? healthCoverageIdList.Count : maxCount2;
for (int j = 0; j < maxCount2; j++)
{
SkipLine = false;
//Custom Code
//if (ChildLoop == "2300")
//{
// WriteWholeLine(line, j, resultLevel2, writer, memRow, memberEnrollment.Where(x => x.Field<object>(Health_Coverage_ID) == healthCoverageIdList[j]).Select(x => x));
//}
//else
//{
//WriteWholeLine(line, j, resultLevel2, writer, memRow, memberEnrollment);
//}
WriteWholeLine(line, j, resultLevel2, writer, memRow);
if (HealthCoverageTbl.Any() && HealthCoverageTbl.Count() > j)
{
HealthCoverageID = Convert.ToString(HealthCoverageTbl.ElementAt(j).Field<string>(Health_Coverage_ID)).Trim();
}
else
{
HealthCoverageID = string.Empty;
}
#region Level 3
var loopLevel3 = (from row in LoopOrder.AsEnumerable()
where row.Field<int>(HIERARCHY_LEVEL) == 3
&& row.Field<string>(PARENT_LOOP).Trim() == ChildLoop.Trim()
select row);
foreach (DataRow level3 in loopLevel3)
{
//Level 3
ChildLoopLevel3 = Convert.ToString(level3[LOOP_ID]);
LoopID = ChildLoopLevel3;
var resultLevel3 = (from row in ValidationElementAttribute.AsEnumerable()
where row.Field<string>(LoopIdSegment).Trim() == ChildLoopLevel3.Trim()
select row);
if (resultLevel3.Any())
{
CobInfoTbl = CobInfoTblMaster.AsEnumerable().Where(x => x.Field<string>(Health_Coverage_ID).Trim() == HealthCoverageID).Select(x => x);
ProviderTbl = ProviderTblMaster.AsEnumerable().Where(x => x.Field<string>(Health_Coverage_ID).Trim() == HealthCoverageID).Select(x => x);
LXcounter = 0;
int maxCount3;
if (String.IsNullOrEmpty(Convert.ToString(level3[Repeat_max])))
maxCount3 = maximumCount;
else
maxCount3 = Convert.ToInt32(level3[Repeat_max]);
for (int k = 0; k < maxCount3; k++)
{
SkipLine = false;
if (CobInfoTbl.Any() && CobInfoTbl.Count() > k)
{
CobInfoID = CobInfoTbl.ElementAt(k).Field<string>(COB_ID);
}
else
{
CobInfoID = Convert.ToString("0");
}
//Not used : uncomment if Provider ID needed.
if (ProviderTbl.Any() && ProviderTbl.Count() > k)
{
ProviderID = ProviderTbl.ElementAt(k).Field<string>(Provider_ID).Trim();
}
else
{
ProviderID = string.Empty;
}
WriteWholeLine(line, k, resultLevel3, writer, memRow);
#region Level 4
var loopLevel4 = (from row in LoopOrder.AsEnumerable()
where row.Field<int>(HIERARCHY_LEVEL) == 4
&& row.Field<string>(PARENT_LOOP).Trim() == ChildLoopLevel3.Trim()
select row);
foreach (DataRow level4 in loopLevel4)
{
//Level 4
ChildLoopLevel4 = Convert.ToString(level4[LOOP_ID]);
LoopID = ChildLoopLevel4;
var resultLevel4 = (from row in ValidationElementAttribute.AsEnumerable()
where row.Field<string>(LoopIdSegment).Trim() == ChildLoopLevel4.Trim()
select row);
if (resultLevel4.Any())
{
int maxCount4;
if (String.IsNullOrEmpty(Convert.ToString(level4[Repeat_max])))
maxCount4 = maximumCount;
else
maxCount4 = Convert.ToInt32(level4[Repeat_max]);
for (int l = 0; l < maxCount4; l++)
{
SkipLine = false;
WriteWholeLine(line, l, resultLevel4, writer, memRow);
}
}
}
#endregion
}
}
}
#endregion
}
}
}
#endregion
}
}
}
// TODO : remove below break
// break;
}
//end of Regeneration
#endregion
return line;
}
if the order of the entries does not matter as in the results of each nested loop dont need to have the structure the foreach source has.
A->B->C->D->E each of those represent a nested loop, you could do it in parallel.
since all data manipulation should be the same, rewrite all foreach as in parallel. save the results to a collection like a ConcurrentDictionary
Related
I have a json array that looks like...
{
"equipment": [{
"date_of_examination": "2022-05-20T14:08:38.072965",
"defect_type": ["DN"],
"eqpt_ref": "AA1",
"eqpt_name": ["2 Leg Chain Sling"],
"eqpt_manufacturer": "Merc",
"eqpt_model": "edes",
"part_no": "A1",
"serial_no": "A1",
"year": "2019",
"swl": "32 tons",
"exam_type": ["6 Months"],
"date_of_last_examination": "2021-11-20T00:00:00",
"date_of_next_examination": "2022-11-20T00:00:00",
"defect": "sling is torn",
"action_required": "replace"
}, {
"date_of_examination": "2022-05-20T14:12:23.997004",
"eqpt_ref": "AA2",
"eqpt_name": ["Other - "],
"eqpt_name_other": "widget",
"eqpt_manufacturer": "merc",
"eqpt_model": "edes",
"part_no": "B1",
"serial_no": "B1",
"year": "2019",
"swl": "32 tons",
"exam_type": ["6 Months"]
}, {
"date_of_examination": "2022-05-20T14:13:24.795136",
"defect_type": ["DF"],
"eqpt_ref": "CC1",
"eqpt_name": ["Endless Round Sling (2.5m)"],
"eqpt_manufacturer": "merc",
"eqpt_model": "edes",
"part_no": "c1",
"serial_no": "c1",
"year": "2019",
"swl": "42 tons",
"exam_type": ["6 Months"],
"defect": "stitching is coming undone",
"danger_value": "6",
"danger_units": ["Weeks"],
"action_required": "needs to be stitched again"
}]
}
I am attempting to loop through the array and filter items as I need, to populate a table later.
The table has three parts.
First, is show all items with a defect_type of "DN". Second is to show all defect_type of "DF", and the last part is to show all the rest (in his case, the one with eqpt_name of AA2)
My original code is...
for (int j = 0; j <= 2; j++)
{
// Note, some table name parts won't have the "Filter..." aspect
// the string below will change depending on which loop we are in.
string[] tableNameParts = "TableStart:equipment:defectNow:Filter:defect_type=DN".Split(':');
string tableNameJson = tableNameParts[1].Replace("»", "");
var jsonRows = IncomingJson[tableNameJson];
if (tableNameParts.Count() > 3)
{
// We probably have a filter set.
if (tableNameParts[3].Replace("»", "").ToLower() == "filter" && tableNameParts.Count() > 4)
{
// These values are not set in stone. It is what values have been set in the JSON, and then matched.
// for example... TableStart:<subform name>:<differentiator>:Filter:<field name>=<field value>
string[] FilterParts = tableNameParts[4].Split('=');
// Get the filter field and value to filter by
if (FilterParts.Count() > 1)
{
string FilterField = FilterParts[0].Replace("»", "");
string FilterValue = FilterParts[1].Replace("»", "");
JArray filteredArray = new JArray();
if (jsonRows[0].GetType() == typeof(JObject))
{
//int loopCount = 0;
foreach (JObject arrayObject in jsonRows) // Each group can have a set of arrays. (each record has multiple sub records)
//for (int i = 0; i < jsonRows.Count(); i++)
{
//JObject arrayObject = jsonRows[i];
foreach (var objectItem in arrayObject)
{
string objectItemValue = string.Empty;
if (objectItem.Value.GetType() == typeof(JArray))
{
foreach (var item in objectItem.Value)
{
objectItemValue += item;
}
}
else
{
objectItemValue = (string)objectItem.Value;
}
if (objectItem.Key == FilterField && objectItemValue == FilterValue)
{
// We need to save the item.
filteredArray.Add(arrayObject);
testArray.Add(arrayObject);
//arrayObject["filtered"] = true;
//IncomingJson[tableNameJson][loopCount]["filtered"] = true;
}
}
//loopCount++;
}
}
else
{
foreach (JArray arrayGroup in jsonRows) // The array group (e.g. fault_record_subform)
{
// We are looking through the json array, to find any rows that match our filter key and filter value.
// We will then add that into our jsonRows
//int loopCount = 0;
foreach (JObject arrayObject in arrayGroup) // Each group can have a set of arrays. (each record has multiple sub records)
{
foreach (var objectItem in arrayObject)
{
string objectItemValue = string.Empty;
if (objectItem.Value.GetType() == typeof(JArray))
{
foreach (var item in objectItem.Value)
{
objectItemValue += item;
}
}
else
{
objectItemValue = (string)objectItem.Value;
}
if (objectItem.Key == FilterField && objectItemValue == FilterValue)
{
// We need to save the item.
filteredArray.Add(arrayObject);
testArray.Add(arrayObject);
//arrayObject["filtered"] = true;
//IncomingJson[tableNameJson][loopCount]["filtered"] = true;
}
}
}
//loopCount++;
}
}
//filteredArray.CopyTo(testArray, 0);
jsonRows = filteredArray; // limit the jsonRows to the filtered set (overwrite the jsonRows)
}
}
}
else
{
// This is not a filter set
JArray singleArray = new JArray();
foreach(var arraySet in jsonRows)
{
if (!testArray.Intersect(arraySet).Any())
{
if (arraySet.GetType() == typeof(JObject))
{
singleArray.Add(arraySet);
}
else
{
foreach (JObject arrayObject in arraySet)
{
singleArray.Add(arrayObject);
}
}
}
}
jsonRows = singleArray;
}
}
By the time it gets to the "this is not a filter set" (which should be the third iteration of the loop), I need to be able to ignore the other filtered items, but as you might see, I have attempted to mark an item as filtered (then filter out). I have also tried to add the filtered items to an alternative array and use that to filter out. All to no avail.
How do I make it so that the "this is not a filter set" rows can ignore the rows already filtered?
=========== EDIT ==============
After reviewing the link from dbc to the fiddler (I don't have an account on there, and don't know how to link to my changes), I have it running in the fiddler with the code below.
JObject json = JObject.Parse(GetJson());
string[] tableNames = {"TableStart:equipment:defectNow:Filter:defect_type=DN","TableStart:equipment:defectFuture:Filter:defect_type=DF","TableStart:equipment:defectNone"};
for (int j = 0; j <= 2; j++)
{
// Note, some table name parts won't have the "Filter..." aspect
// the string below will change depending on which loop we are in.
string[] tableNameParts = tableNames[j].Split(':');
string tableNameJson = tableNameParts[1].Replace("»", "");
var jsonRows = json[tableNameJson];
if (tableNameParts.Count() > 3)
{
// We probably have a filter set.
if (tableNameParts[3].Replace("»", "").ToLower() == "filter" && tableNameParts.Count() > 4)
{
// These values are not set in stone. It is what values have been set in the JSON, and then matched.
// for example... TableStart:<subform name>:<differentiator>:Filter:<field name>=<field value>
string[] FilterParts = tableNameParts[4].Split('=');
// Get the filter field and value to filter by
if (FilterParts.Count() > 1)
{
string FilterField = FilterParts[0].Replace("»", "");
string FilterValue = FilterParts[1].Replace("»", "");
JArray filteredArray = new JArray();
if (jsonRows[0].GetType() == typeof(JObject))
{
//int loopCount = 0;
foreach (JObject arrayObject in jsonRows) // Each group can have a set of arrays. (each record has multiple sub records)
//for (int i = 0; i < jsonRows.Count(); i++)
{
//JObject arrayObject = jsonRows[i];
foreach (var objectItem in arrayObject)
{
string objectItemValue = string.Empty;
if (objectItem.Value.GetType() == typeof(JArray))
{
foreach (var item in objectItem.Value)
{
objectItemValue += item;
}
}
else
{
objectItemValue = (string)objectItem.Value;
}
if (objectItem.Key == FilterField && objectItemValue == FilterValue)
{
// We need to save the item.
filteredArray.Add(arrayObject);
//testArray.Add(arrayObject);
//arrayObject["filtered"] = true;
//IncomingJson[tableNameJson][loopCount]["filtered"] = true;
}
}
//loopCount++;
}
}
else
{
foreach (JArray arrayGroup in jsonRows) // The array group (e.g. fault_record_subform)
{
// We are looking through the json array, to find any rows that match our filter key and filter value.
// We will then add that into our jsonRows
//int loopCount = 0;
foreach (JObject arrayObject in arrayGroup) // Each group can have a set of arrays. (each record has multiple sub records)
{
foreach (var objectItem in arrayObject)
{
string objectItemValue = string.Empty;
if (objectItem.Value.GetType() == typeof(JArray))
{
foreach (var item in objectItem.Value)
{
objectItemValue += item;
}
}
else
{
objectItemValue = (string)objectItem.Value;
}
if (objectItem.Key == FilterField && objectItemValue == FilterValue)
{
// We need to save the item.
filteredArray.Add(arrayObject);
//testArray.Add(arrayObject);
//arrayObject["filtered"] = true;
//IncomingJson[tableNameJson][loopCount]["filtered"] = true;
}
}
}
//loopCount++;
}
}
//filteredArray.CopyTo(testArray, 0);
jsonRows = filteredArray; // limit the jsonRows to the filtered set (overwrite the jsonRows)
}
}
}
else
{
// This is not a filter set
JArray singleArray = new JArray();
foreach(var arraySet in jsonRows)
{
//if (!testArray.Intersect(arraySet).Any())
{
if (arraySet.GetType() == typeof(JObject))
{
singleArray.Add(arraySet);
}
else
{
foreach (JObject arrayObject in arraySet)
{
singleArray.Add(arrayObject);
}
}
}
}
jsonRows = singleArray;
}
}
What I need ultimately (the jsonRows will be used elsewhere in my code within the loop) is that the third set will have items not found in the first 2 sets.
After a bit of further experimentation, using dotnetfiddle as introduced to me by #dbc (thank you), I have created a List and added each arrayObject into the list during the filtering stages.
I then during the unfiltered stage check if my arraySet is contained in the List, and if not, then add that item to the remaining jsonRows, thereby giving me the balance of the original list.
As can be seen here...
https://dotnetfiddle.net/ot35Z2
I want skip my in foreach. For example:
foreach(Times t in timeList)
{
if(t.Time == 20)
{
timeList.Skip(3);
}
}
I want "jump" 3 positions in my list.. If, in my if block t.Id = 10 after skip I want get t.Id = 13
How about this? If you use a for loop then you can just step the index forward as needed:
for (var x = 0; x < timeList.Length; x++)
{
if (timeList[x].Time == 20)
{
// option 1
x += 2; // 'x++' in the for loop will +1,
// we are adding +2 more to make it 3?
// option 2
// x += 3; // just add 3!
}
}
You can't modify an enumerable in-flight, as it were, like you could the index of a for loop; you must account for it up front. Fortunately there are several way to do this.
Here's one:
foreach(Times t in timeList.Where(t => t.Time < 20 || t.Time > 22))
{
}
There's also the .Skip() option, but to use it you must break the list into two separate enumerables and then rejoin them:
var times1 = timeList.TakeWhile(t => t.Time != 20);
var times2 = timeList.SkipeWhile(t => t.Time != 20).Skip(3);
foreach(var t in times1.Concat(times2))
{
}
But that's not exactly efficient, as it requires iterating over the first part of the sequence twice (and won't work at all for Read Once -style sequences). To fix this, you can make a custom enumerator:
public static IEnumerable<T> SkipAt<T>(this IEnumerable<T> items, Predicate<T> SkipTrigger, int SkipCount)
{
bool triggered = false;
int SkipsRemaining = 0;
var e = items.GetEnumerator();
while (e.MoveNext())
{
if (!triggered && SkipTrigger(e.Current))
{
triggered = true;
SkipsRemaining = SkipCount;
}
if (triggered)
{
SkipsRemaining--;
if (SkipsRemaining == 0) triggered = false;
}
else
{
yield return e.Current;
}
}
}
Then you could use it like this:
foreach(Times t in timeList.SkipAt(t => t.Times == 20, 3))
{
}
But again: you still need to decide about this up front, rather than inside the loop body.
For fun, I felt like adding an overload that uses another predicate to tell the enumerator when to resume:
public static IEnumerable<T> SkipAt<T>(this IEnumerable<T> items, Predicate<T> SkipTrigger, Predicate<T> ResumeTrigger)
{
bool triggered = false;
var e = items.GetEnumerator();
while (e.MoveNext())
{
if (!triggered && SkipTrigger(e.Current))
{
triggered = true;
}
if (triggered)
{
if (ResumeTrigger(e.Current)) triggered = false;
}
else
{
yield return e.Current;
}
}
}
You can use continue with some simple variables.
int skipCount = 0;
bool skip = false;
foreach (var x in myList)
{
if (skipCount == 3)
{
skip = false;
skipCount = 0;
}
if (x.time == 20)
{
skip = true;
skipCount = 0;
}
if (skip)
{
skipCount++;
continue;
}
// here you do whatever you don't want to skip
}
Or if you can use a for-loop, increase the index like this:
for (int i = 0; i < times.Count)
{
if (times[i].time == 20)
{
i += 2; // 2 + 1 loop increment
continue;
}
// here you do whatever you don't want to skip
}
I have a search query which search for all jobs in the database and than displays them in accordance to the most recent ones filtering the data by date as follows:
result = db.AllJobModel.Where(a => a.JobTitle.Contains(searchTitle) && a.locationName.Contains(searchLocation)).ToList());
result = (from app in result orderby DateTime.ParseExact(app.PostedDate, "dd/MM/yyyy", null) descending select app).ToList();
result = GetAllJobModelsOrder(result);
after that I have a method GetAllJobModelsOrder which displays jobs in order which seems to be work fine but in my case its not ordering jobs so I need to understand where I am wrong:
private List<AllJobModel> GetAllJobModelsOrder(List<AllJobModel> result)
{
var list = result.OrderBy(m => m.JobImage.Contains("job1") ? 1 :
m.JobImage.Contains("job2") ? 2 :
m.JobImage.Contains("job3") ? 3 :
m.JobImage.Contains("job4") ? 4 :
m.JobImage.Contains("job5") ? 5 :
6)
.ToList();
return list;
}
The result I get is about 10 jobs from job1 and than followed by other jobs in the same order what I would like to achieve is to filter the most recent jobs than display one job from each type of a job.
An example of the input would be as follows:
AllJobModel allJobModel = new AllJobModel
{
JobDescription = "Description",
JobImage = "Job1",
JobTitle = "title",
locationName = "UK",
datePosted = "15/06/2020",
}
The output that I get is as follows:
In where result should be mixed from different jobs.
Excepted resulta as follows a specific order of job source--1. TotalJob[0] :: 2. MonsterJob[0] :: 3. Redd[0] :: 4. TotalJob[ 1 ] :: 5. MonsterJob[ 1 ] ::6. Redd[ 1 ]:
I have tried the following solution but list data structure seems to be not stroing data in order:
private List<AllJobModel> GetAllJobModelsOrder(List<AllJobModel> result)
{
string lastItem = "";
List<AllJobModel> list = new List<AllJobModel>();
int pos = -1;
while(result.Count != 0)
{
for(int i = 0; i < result.Count; i++)
{
if(result[i].JobImage.Contains("reed") && (lastItem == "" || lastItem == "total" || lastItem == "monster"))
{
pos++;
list.Insert(pos,result[i]);
lastItem = "reed";
result.Remove(result[i]);
break;
}else if (result[i].JobImage.Contains("total") && (lastItem == "reed" || lastItem == "monster" || lastItem == "" ))
{
pos++;
list.Insert(pos, result[i]);
lastItem = "total";
result.Remove(result[i]);
break;
}else if(result[i].JobImage.Contains("monster.png") && (lastItem =="total" || lastItem == "reed" || lastItem == "" ))
{
pos++;
list.Insert(pos, result[i]);
lastItem = "monster";
result.Remove(result[i]);
break;
}else if(result[i].JobImage.Contains("reed") &&( lastItem == "reed"))
{
if(result.FirstOrDefault(a=>a.JobImage.Contains("total") || a.JobImage.Contains("monster")) != null)
{
lastItem = "total";
break;
}
else
{
pos++;
list.Insert(pos, result[i]);
lastItem = "reed";
result.Remove(result[i]);
break;
}
}
else if (result[i].JobImage.Contains("total") && (lastItem == "total"))
{
if (result.FirstOrDefault(a => a.JobImage.Contains("reed") || a.JobImage.Contains("monster")) != null)
{
lastItem = "monster";
break;
}
else
{
pos++;
list.Insert(pos, result[i]);
lastItem = "total";
result.Remove(result[i]);
break;
}
}
else if (result[i].JobImage.Contains("monster") && (lastItem == "monster"))
{
if (result.FirstOrDefault(a => a.JobImage.Contains("total") || a.JobImage.Contains("reed")) != null)
{
lastItem = "reed";
break;
}
else
{
pos++;
list.Insert(pos, result[i]);
lastItem = "monster";
result.Remove(result[i]);
break;
}
}
}
}
return list;
}
also what I found is that the value of the elements in the list is different from what its actual value. So I am not sure if this is an error with my code or with visual studio:
you can use the below concept here. I am sorting a list based on the numeric value at the end of each string value using Regex.
List<string> ls = new List<string>() { "job2", "job1", "job4", "job3" };
ls = ls.OrderBy(x => Regex.Match(x, #"\d+$").Value).ToList();
Certainly the requirement was not as straight forward as initially thought. Which is why I am offering a second solution.
Having order by and rotate the offering "Firm" in a type of priority list for a set number of times and then just display whatever comes after that requires a custom solution. If the one algorithm you have works and you are happy then great. Otherwise, I have come up with this algorithm.
private static List<AllJobModel> ProcessJobs(List<AllJobModel> l)
{
var noPriorityFirst = 2;
var orderedList = new List<AllJobModel>();
var priorityImage = new string[] { "TotalJob", "MonsterJob", "Redd" };
var gl = l.OrderBy(o => o.datePosted).GroupBy(g => g.datePosted).ToList();
foreach (var g in gl)
{
var key = g.Key;
for (int i = 0; i < noPriorityFirst; i++)
{
foreach (var j in priorityImage)
{
var a = l.Where(w => w.datePosted.Equals(key) && w.JobImage.Equals(j)).FirstOrDefault();
if (a != null)
{
orderedList.Add(a);
var ra = l.Remove(a);
}
}
}
foreach (var j in l.ToList())
{
var a = l.Where(w => w.datePosted.Equals(key)).FirstOrDefault();
if (a != null)
{
orderedList.Add(a);
var ra = l.Remove(a);
}
}
}
return orderedList;
}
To test this process I have created this Console app:
static void Main(string[] args)
{
Console.WriteLine("Start");
var l = CreateTestList();
var lJobs = ProcessJobs(l);
lJobs.ForEach(x => Console.WriteLine($"{x.datePosted} : {x.JobImage}"));
}
private static List<AllJobModel> CreateTestList()
{
var orderedList = new List<AllJobModel>();
var l = new List<AllJobModel>();
var priorityImage = new string[] { "TotalJob", "MonsterJob", "Redd" };
var rand = new Random();
var startTime = DateTime.Now;
for (int i = 0; i < 20; i++)
{
var j = rand.Next(0, priorityImage.Length);
var h = rand.Next(0, 4);
var a = new AllJobModel();
a.JobDescription = "Desc " + i;
a.JobImage = priorityImage[j];
a.JobTitle = "Title" + i;
a.locationName = "UK";
a.datePosted = startTime.AddDays(h);
l.Add(a);
}
for (int i = 0; i < 20; i++)
{
var j = rand.Next(0, priorityImage.Length);
var h = rand.Next(0, 4);
var a = new AllJobModel();
a.JobDescription = "Desc " + i;
a.JobImage = "Job " + i;
a.JobTitle = "Title" + i;
a.locationName = "UK";
a.datePosted = startTime.AddDays(h);
l.Add(a);
}
return l;
}
I know this is a dumb question because you cannot modify the loop collection while in a loop, but I do need to change it. I know I must not change the referenced objects, but I have no idea how to do this.
var orders = _orderService.GetOrders(o => !o.Deleted &&
o.OrderStatus != OrderStatus.Cancelled &&
o.OrderStatus != OrderStatus.Complete);
foreach (var order in orders)
{
if (order.PaymentStatus == PaymentStatus.Paid)
{
if (order.ShippingStatus == ShippingStatus.ShippingNotRequired || order.ShippingStatus == ShippingStatus.Delivered)
{
var tempOrder = _orderService.GetOrderById(order.Id);
SetOrderStatus(tempOrder , OrderStatus.Complete, true);
}
}
}
I always get an error.
UPDATED: I changed to this
var orders = _orderService.GetOrders(o => !o.Deleted &&
o.OrderStatus != OrderStatus.Cancelled && o.OrderStatus != OrderStatus.CompletE);
List<int> orderIndex = new List<int>();
orders.ToList().ForEach(x => orderIndex.Add(x.Id));
foreach(var index in orderIndex)
{
var order = _orderService.GetOrderById(index);
if (order.PaymentStatus == PaymentStatus.Paid)
{
if (order.ShippingStatus == ShippingStatus.ShippingNotRequired || order.ShippingStatus == ShippingStatus.Delivered)
{
SetOrderStatus(order, OrderStatus.Complete, true);
}
}
}
try
int count = orders.Count; // the length of the collect : may need a different method for different collection types.
for(int i = 0; i < count; i++)
{
var current = orders[i];
// do stuff with current.
}
use for loop instead of foreach loop
for(int i=0; i<orders.Count; i++)
{
if (orders[i].PaymentStatus == PaymentStatus.Paid)
{
if (orders[i].ShippingStatus == ShippingStatus.ShippingNotRequired || orders[i].ShippingStatus == ShippingStatus.Delivered)
{
var tempOrder = _orderService.GetOrderById(orders[i].Id);
SetOrderStatus(tempOrder , OrderStatus.Complete, true);
}
}
}
I have a DataTable that has the following structure:
Root | Level 1 | Level 2 | Level 3 | Tree L | Tree R
Food 1 18
Fruit 2 11
Red 3 6
Cherry 4 5
Yellow 7 10
Banana 8 9
Meat 12 17
Beef 13 14
Pork 15 16
Using C#, I need to traverse this structure and calculate the correct Tree L and Tree R values for each node. This is just an example, the real structure has several hundred nodes that go out to at least Level 7, but possibly more.
Can anyone suggest how I might approach the code for calculating the left and right values?
So, you want to keep track of the visit order of the tree, but you have the order split into L and R. Those correspond to the "entrance" and "exit" of the Visit function for the Node structure. Assuming a Node class with a Node.Visit() method, you could:
private static List<Tuple<char,Node>> VisitOrder = new List<Tuple<char,Node>>();
public void Visit()
{
VisitOrder.Add(Tuple.Create('L', this));
// whatever visit logic you use here
VisitOrder.Add(Tuple.Create('R', this));
}
When you finish, all you have to do is do is look at the VisitOrder values. They're stored in the List in increasing order, where the index corresponds to it's position in the visit sequence. Each item in the List, then, is a Tuple describing which value it corresponds to and which Node it visited.
Edit:
To get the final output format, you could then do something like:
var LTree = VisitOrder
.Where(t => t.First == 'L')
.Select((t, i) => String.Format("{0}) {1}", i + 1, t.Second.Name));
var RTree = VisitOrder
.Where(t => t.First == 'R')
.Select((t, i) => String.Format("{0}) {1}", i + 1, t.Second.Name));
Here is how I figured it out:
private class FolderRow
{
public int Indent
{
get { return this.Row.GetValue("Indent", 0); }
set { this.Row["Indent"] = value; }
}
public int Left
{
get { return this.Row.GetValue("Tree L", 0); }
set { this.Row["Tree L"] = value; }
}
public int Right
{
get { return this.Row.GetValue("Tree R", 0); }
set { this.Row["Tree R"] = value; }
}
public Guid Id
{
get { return this.Row.GetValue("FolderID", Guid.Empty); }
}
public DataRow Row { get; private set; }
public int RowNum { get; set; }
public bool RowComplete { get { return this.Left > 0 && this.Right > 0; } }
public FolderRow(DataRow row, int rowNum)
{
this.Row = row;
this.RowNum = rowNum;
}
}
[TestMethod]
public void ImportFolderStructure()
{
var inputTable = FileUtil.GetDataSetFromExcelFile(new FileInfo(#"c:\SampleTree.xlsx")).Tables[0];
var currentLevel = 0;
var nodeCount = 1;
var currentRow = 0;
inputTable.Columns.Add("Indent", typeof (int));
inputTable.Columns.Add("Path", typeof (string));
var rightStack = new List<FolderRow>();
foreach (DataRow row in inputTable.Rows)
row["Indent"] = GetLevelPopulated(row);
foreach (DataRow row in inputTable.Rows)
{
if (row.GetValue("Indent", 0) == 0)
row["Tree L"] = 1;
}
while (true)
{
var row = GetRow(inputTable, currentRow);
if (row.Indent == 0)
{
currentRow++;
rightStack.Add(row);
continue;
}
// if the indent of this row is greater than the previous row ...
if (row.Indent > currentLevel)
{
currentLevel++;
nodeCount++;
row.Left = nodeCount;
// ... check the next row to see if it is further indented
currentRow = HandleNextRow(row, currentRow, rightStack, inputTable, ref currentLevel, ref nodeCount);
} else if (row.Indent == currentLevel)
{
nodeCount++;
row.Left = nodeCount;
currentRow = HandleNextRow(row, currentRow, rightStack, inputTable, ref currentLevel, ref nodeCount);
} else if (row.Indent < currentLevel)
{
currentLevel--;
nodeCount++;
row.Left = nodeCount;
currentRow = HandleNextRow(row, currentRow, rightStack, inputTable, ref currentLevel, ref nodeCount);
}
if (inputTable.Rows.Cast<DataRow>().Select(r => new FolderRow(r, -1)).All(r => r.RowComplete))
break;
}
}
private int HandleNextRow(FolderRow row, int currentRow, List<FolderRow> rightStack, DataTable inputTable, ref int currentLevel,
ref int nodeCount)
{
var nextRow = GetRow(inputTable, currentRow + 1);
if (nextRow != null)
{
if (nextRow.Indent > row.Indent)
{
// ok the current row has a child so we will need to set the tree right of that, add to stack
rightStack.Add(row);
}
else if (nextRow.Indent == row.Indent)
{
nodeCount++;
row.Right = nodeCount;
}
else if (nextRow.Indent < row.Indent)
{
nodeCount++;
row.Right = nodeCount;
nodeCount++;
// here we need to get the most recently added row to rightStack, set the Right to the current nodeCount
var stackLast = rightStack.LastOrDefault();
if (stackLast != null)
{
stackLast.Right = nodeCount;
rightStack.Remove(stackLast);
}
currentLevel--;
}
currentRow++;
if (rightStack.Count > 1)
{
// before we move on to the next row, we need to check if there is more than one row still in right stack and
// the new current row's ident is less than the current branch (not current leaf)
var newCurrentRow = GetRow(inputTable, currentRow);
var stackLast = rightStack.LastOrDefault();
if (newCurrentRow.Indent == stackLast.Indent)
{
nodeCount++;
stackLast.Right = nodeCount;
rightStack.Remove(stackLast);
}
}
}
else
{
// reached the bottom
nodeCount++;
row.Right = nodeCount;
// loop through the remaining items in rightStack and set their right values
var stackLast = rightStack.LastOrDefault();
while (stackLast != null)
{
nodeCount++;
stackLast.Right = nodeCount;
rightStack.Remove(stackLast);
stackLast = rightStack.LastOrDefault();
}
}
return currentRow;
}
private FolderRow GetRow(DataTable inputTable, int rowCount)
{
if (rowCount >= inputTable.Rows.Count)
return null;
return rowCount < 0 ? null : new FolderRow(inputTable.Rows[rowCount],rowCount);
}
private int GetLevelPopulated(DataRow row)
{
var level = 0;
while (level < 14)
{
if (level == 0 && row["Root"] != DBNull.Value)
return level;
level++;
if (row["Level " + level] != DBNull.Value)
return level;
}
return -1;
}