How can I simplify my nested for loops - c#

I want to make my code short and simple using linq.
I have a list that contains leaveDates and every leaveDates contain number of leavelist.
Something like this:
{ leaves_date = {07-05-2018 18:30:00}, LeaveList = {System.Collections.Generic.List<TimeClock.Model.LeaveManagementModel>} }
{ leaves_date = {08-05-2018 18:30:00}, LeaveList = {System.Collections.Generic.List<TimeClock.Model.LeaveManagementModel>} }
{ leaves_date = {21-05-2018 18:30:00}, LeaveList = {System.Collections.Generic.List<TimeClock.Model.LeaveManagementModel>} }
leaveList contains UserId, LeaveType, Status fields
Now all I want is to count the number of leavedates per user who's status is 1 and leave type != 3
I have already tried using a for loop, but I want to do it with linq.
Here is my code with the for loop:
for (var i = 0; i < leavesresult.Count; i++) {
for (var a = 0; a < leavesresult[i].LeaveList.Count; a++) {
if (leavesresult[i].LeaveList[a].status == 1.ToString() && leavesresult[i].LeaveList[a].leave_type != 3.ToString()) {
var compair1 = leavesresult[i].LeaveList[a].user_id;
var compair2 = attendancelist.Any(z = >z.user_id == leavesresult[i].LeaveList[a].user_id);
if (attendancelist.Any(z = >z.user_id == leavesresult[i].LeaveList[a].user_id)) {
int index = attendancelist.FindIndex(y = >y.user_id == leavesresult[i].LeaveList[a].user_id);
if (leavesresult[i].LeaveList[a].check_halfday == 1) {
attendancelist[index].days = attendancelist[index].days
}
else {
attendancelist[index].days = attendancelist[index].days + 1;
}
}
else {
if (leavesresult[i].LeaveList[a].check_halfday == 1) {
attendancelist.Add(new AttendanceModel {
user_id = leavesresult[i].LeaveList[a].user_id,
days = 0.5
});
}
else {
attendancelist.Add(new AttendanceModel {
user_id = leavesresult[i].LeaveList[a].user_id,
days = 1
});
}
}
}
}
}

I could give you the query and you would learn nothing. Instead learn how to do this transformation yourself. The trick is to not try to do it all at once. Rather, we make a series of small, obviously correct transformations each one of which gets us closer to our goal.
Start by rewriting the inner for loop as a foreach:
for (var i = 0; i < leavesresult.Count; i++)
{
foreach (var leavelist in leavesresult[i].LeaveList)
{
if (leavelist.status == 1.ToString() && leavelist.leave_type != 3.ToString())
{
var compair1 = leavelist.user_id;
var compair2 = attendancelist.Any(z => z.user_id == leavelist.user_id);
if (attendancelist.Any(z => z.user_id == leavelist.user_id))
{
int index = attendancelist.FindIndex(y => y.user_id == leavelist.user_id);
if (leavelist.check_halfday == 1)
attendancelist[index].days = attendancelist[index].days
else
attendancelist[index].days = attendancelist[index].days + 1;
}
else
{
if (leavelist.check_halfday == 1)
attendancelist.Add(
new AttendanceModel {user_id = leavelist.user_id, days = 0.5});
else
attendancelist.Add(
new AttendanceModel {user_id = leavelist.user_id, days = 1});
}
}
}
}
Already your code is about 100 times easier to read with that change.
Now we notice a few things:
if (leavelist.status == 1.ToString() && leavelist.leave_type != 3.ToString())
That is a crazy way to write this check. Rewrite it into a sensible check.
var compair1 = leavelist.user_id;
var compair2 = attendancelist.Any(z => z.user_id == leavelist.user_id);
Neither of these variables are ever read, and their initializers are useless. Delete the second one. Rename the first one to user_id.
if (leavelist.check_halfday == 1)
attendancelist[index].days = attendancelist[index].days
else
attendancelist[index].days = attendancelist[index].days + 1;
The consequence makes no sense. Rewrite this.
OK, we now have
for (var i = 0; i < leavesresult.Count; i++)
{
foreach (var leavelist in leavesresult[i].LeaveList)
{
if (leavelist.status == "1" && leavelist.leave_type != "3")
{
var user_id= leavelist.user_id;
if (attendancelist.Any(z => z.user_id == leavelist.user_id))
{
int index = attendancelist.FindIndex(y => y.user_id == leavelist.user_id);
if (leavelist.check_halfday != 1)
attendancelist[index].days = attendancelist[index].days + 1;
}
else
{
if (leavelist.check_halfday == 1)
attendancelist.Add(
new AttendanceModel {user_id = leavelist.user_id, days = 0.5});
else
attendancelist.Add(
new AttendanceModel {user_id = leavelist.user_id, days = 1});
}
}
}
}
Use the helper variable throughout:
for (var i = 0; i < leavesresult.Count; i++)
{
foreach (var leavelist in leavesresult[i].LeaveList)
{
if (leavelist.status == "1" && leavelist.leave_type != "3")
{
var user_id = leavelist.user_id;
if (attendancelist.Any(z => z.user_id == user_id))
{
int index = attendancelist.FindIndex(y => y.user_id == user_id);
if (leavelist.check_halfday != 1)
attendancelist[index].days = attendancelist[index].days + 1;
}
else
{
if (leavelist.check_halfday == 1)
attendancelist.Add(
new AttendanceModel {user_id = user_id, days = 0.5});
else
attendancelist.Add(
new AttendanceModel {user_id = user_id, days = 1});
}
}
}
}
We realize that the Any and the FindIndex are doing the same thing. Eliminate one of them:
for (var i = 0; i < leavesresult.Count; i++)
{
foreach (var leavelist in leavesresult[i].LeaveList)
{
if (leavelist.status == "1" && leavelist.leave_type != "3")
{
var user_id = leavelist.user_id;
int index = attendancelist.FindIndex(y => y.user_id == user_id);
if (index != -1)
{
if (leavelist.check_halfday != 1)
attendancelist[index].days = attendancelist[index].days + 1;
}
else
{
if (leavelist.check_halfday == 1)
attendancelist.Add(
new AttendanceModel {user_id = user_id, days = 0.5});
else
attendancelist.Add(
new AttendanceModel {user_id = user_id, days = 1});
}
}
}
}
We notice that we are duplicating code in the final if-else. The only difference is days:
for (var i = 0; i < leavesresult.Count; i++)
{
foreach (var leavelist in leavesresult[i].LeaveList)
{
if (leavelist.status == "1" && leavelist.leave_type != "3")
{
var user_id = leavelist.user_id;
int index = attendancelist.FindIndex(y => y.user_id == user_id);
if (index != -1)
{
if (leavelist.check_halfday != 1)
attendancelist[index].days = attendancelist[index].days + 1;
}
else
{
double days = leavelist.check_halfday == 1 ? 0.5 : 1;
attendancelist.Add(new AttendanceModel {user_id = user_id, days = days});
}
}
}
}
Now your code is 1000x easier to read than it was before. Keep going! Rewrite the outer loop as a foreach:
foreach (var lr in leavesresult)
{
foreach (var leavelist in lr.LeaveList)
{
if (leavelist.status == "1" && leavelist.leave_type != "3")
{
var user_id = leavelist.user_id;
int index = attendancelist.FindIndex(y => y.user_id == user_id);
if (index != -1)
{
if (leavelist.check_halfday != 1)
attendancelist[index].days = attendancelist[index].days + 1;
}
else
{
double days = leavelist.check_halfday == 1 ? 0.5 : 1;
attendancelist.Add(new AttendanceModel {user_id = user_id, days = days});
}
}
}
}
And we notice a couple more things: we can put check_halfday into an explanatory variable, and eliminate days. And we can simplify the increment:
foreach (var lr in leavesresult)
{
foreach (var leavelist in lr.LeaveList)
{
if (leavelist.status == "1" && leavelist.leave_type != "3")
{
var user_id = leavelist.user_id;
int index = attendancelist.FindIndex(y => y.user_id == user_id);
bool halfday= leavelist.check_halfday == 1;
if (index != -1)
{
if (!halfday)
attendancelist[index].days += 1;
}
else
{
attendancelist.Add(new AttendanceModel {user_id = user_id, days = halfday ? 0.5 : 1});
}
}
}
}
Now we begin transforming this to a query. The key thing to understand is that mutations must not go in queries. Mutations only go into loops, never queries. Queries ask questions, they do not perform mutations.
You have a mutation of attendancelist, so that's got to stay in a loop. But we can move all the query logic out of the loop by recognizing that the nested foreach with a test inside the inner loop is equivalent to:
var query = from lr in leaveresult
from ll in lr.LeaveList
where ll.status == "1"
where ll.leave_type != "3"
select ll;
Excellent. Now we can use that in our foreach:
foreach(var ll in query)
{
var index = attendancelist.FindIndex(y => y.user_id == ll.user_id);
var halfday = ll.check_halfday == 1;
if (index != -1)
{
if (!halfday)
attendancelist[index].days += 1;
}
else
{
attendancelist.Add(
new AttendanceModel {user_id = ll.user_id, days = halfday? 0.5 : 1 });
}
}
Now that we have the loop in this extremely simple form, we notice that we can re-order the if to simplify it:
foreach(var ll in query)
{
var index = attendancelist.FindIndex(y => y.user_id == ll.user_id);
var halfday = ll.check_halfday == 1;
if (index == -1)
attendancelist.Add(
new AttendanceModel {user_id = ll.user_id, days = halfday? 0.5 : 1 });
else if (!halfday)
attendancelist[index].days += 1;
}
And we're done. All the computation is done by the query, all the mutations are done by the foreach, as it should be. And your loop body is now a single, extremely clear conditional statement.
This answer is to answer your question, which was how to convert an existing bunch of hard-to-read loops into an easy-to-read query. But it would be better still to write a query that clearly expressed the business logic you're trying to implement, and I don't know what that is. Create your LINQ queries so that they make it easy to understand what is happening at the business level.
In this case what I suspect you are doing is maintaining a per-user count of days, to be updated based on the leave lists. So let's write that!
// dict[user_id] is the accumulated leave.
var dict = new Dictionary<int, double>();
var query = from lr in leaveresult
from ll in lr.LeaveList
where ll.status == "1"
where ll.leave_type != "3"
select ll;
foreach(var ll in query)
{
var halfday = ll.check_halfday == 1;
if (!dict.ContainsKey(ll.user_id))
dict[ll.user_id] = halfday? 0.5 : 1;
else if (!halfday)
dict[ll.user_id] = dict[ll.user_id] + 1;
}
That seems like a nicer way to represent this than a list that you are constantly having to search.
Once we are at this point we can then recognize that what you are really doing is computing a per-user sum! The answer by JamieC shows that you can use the Aggregate helper method to compute a per-user sum.
But again, this is based on the assumption that you have built this whole mechanism to compute that sum. Again: design your code so that it clearly implements the business process in the jargon of that process. If what you're doing is computing that sum, boy, does that ever not show up in your original code. Strive to make it clearer what your code is doing.

This is basically 1 line of linq with a groupby, I'm not sure ill get it spot on with 1 try, but something along the lines of:
var attendancelist = leavesresult
.SelectMany(a => a.LeaveList) // flatten the list
.Where(a => a.status == "1" && a.type != "3") // pick the right items
.GroupBy(a => a.user_id) // group by users
.Select(g => new AttendanceModel(){ // project the model
user_id = g.Key,
days = g.Aggregate(0, (a,b) => a + (b.check_halfday == 1 ? 0.5 : 1))
})
.ToList();
Let me know any issues, and i'll try to fix as necessary.
edit1: Assuming AttendanceModel.days is an int you need to decide what to do as it is calculating a float.
Perhaps something like:
...
days = (int)Math.Ceiling(g.Aggregate(0, (a,b) => a + (b.check_halfday == 1 ? 0.5 : 1)))
...

Not a linq version but used foreach to simplify and make it more readable
var userLeaves = new Dictionary<int, double>();
foreach( var lr in leavesresult)
{
foreach (var leave in lr.LeaveList)
{
if (leave.Status == "1" && leave.LeaveType != "3")
{
var leaveDay = leave.check_halfday ==1 ? 0.5 : 1;
if (userLeaves.ContainsKey(leave.UserID))
userLeaves[leave.UserID] = userLeaves[leave.UserID] + leaveDay;
else
userLeaves.Add(leave.UserID, leaveDay);
}
}
}

Related

What is the value of arg in Task.Factory.StartNew

I have Task.Factory.StartNew in C# code with args argument. I am not quite understand what value will arg be. So what value will args be and how the value is determined?
int count = table.Rows.Count;
Dictionary<int, string> expDic = new Dictionary<int, string>();
List<Task> taskList = new List<Task>();
for (int f = 0; f < count; f++)
{
DataRow tempformula = table.Rows[f];
string formulaSymbol = Convert.ToString(tempformula[Common.Systems.Sustainability.Constants.IndicatorFormula.Symbol]);
var t = Task.Factory.StartNew(new Action<object>((args) => {
int i = (int)args;
_sem.Wait();
StringBuilder expression = new StringBuilder(1024);
DataRow formula = table.Rows[i];
int indID = Convert.ToInt32(formula[Common.Systems.Sustainability.Constants.IndicatorFormula.IndicatorID]);
int sequence = Convert.ToInt32(formula[Common.Systems.Sustainability.Constants.IndicatorFormula.Sequence]);
int? referenceIndID = Common.Util.TryToConvertToInt32(formula, Common.Systems.Sustainability.Constants.IndicatorFormula.ReferenceIndicatorID);
decimal? val = Common.Util.TryToConvertToDecimal(formula, Common.Systems.Sustainability.Constants.IndicatorFormula.Value);
string symbol = Convert.ToString(formula[Common.Systems.Sustainability.Constants.IndicatorFormula.Symbol]);
string formulaOutputUnit = Convert.ToString(formula[Common.Systems.Sustainability.Constants.Indicator.Unit]);
if (!string.IsNullOrWhiteSpace(callerAcceptedUnit)) // added by HC on 2016-05-27
{
formulaOutputUnit = callerAcceptedUnit;
}
if (referenceIndID == null)
{
if (val == null)
{
DataSet indicator = GetIndicatorByIDFromCache(companyID, indID); // added by HC on 2017-05-12, for performance tuning.
//using (DataSet indicator = indicatorMgr.GetIndicatorByID(companyID, indID))
{
DataRow dr = indicator.Tables[0].Rows[0];
int indicatorType = Convert.ToInt32(dr[Common.Systems.Sustainability.Constants.Indicator.IndicatorType]);
if (indicatorType == (int)Common.Systems.Sustainability.Constants.IndicatorTypes.Currency
|| indicatorType == (int)Common.Systems.Sustainability.Constants.IndicatorTypes.Numeric)
{
decimal? total = SumTotal(companyID, indID, indicatorType, fromDate, toDate, formulaOutputUnit, callerIndicatorID, breakToMonthly, specifiedLocations, approvalStatus
, usageDataSet, interval
, indicatorIDsChain
, allowNull
);
expression.Append(total.ToString());
}
else if (symbol == "+"
|| symbol == "-"
|| symbol == "*"
|| symbol == "/")
{
expression.Append(symbol);
}
}
}
else
{
expression.Append(val.ToString());
}
}
else
{
string exp = GetExpression(companyID, fromDate, toDate, referenceIndID.Value.ToString(), indID.ToString(), formulaOutputUnit, breakToMonthly, specifiedLocations, approvalStatus
, usageDataSet, interval
, indicatorIDsChain
);
//expression.Append(exp);
using (DataTable dt = new DataTable())
{
// fault tolerance, for in-case users assigned symbol in the last line of formula
if (exp.EndsWith("+")
|| exp.EndsWith("-")
|| exp.EndsWith("*")
|| exp.EndsWith("/"))
{
exp = exp.Substring(0, exp.Length - 1);
}
object result = dt.Compute(exp, "");
expression.Append(result);
}
} // end if (referenceIndID == null)...
if ("IF".Equals(symbol, StringComparison.OrdinalIgnoreCase)
|| "THEN".Equals(symbol, StringComparison.OrdinalIgnoreCase)
|| "ELSE IF".Equals(symbol, StringComparison.OrdinalIgnoreCase)
|| "ELSE".Equals(symbol, StringComparison.OrdinalIgnoreCase)
|| ">".Equals(symbol, StringComparison.OrdinalIgnoreCase)
|| ">=".Equals(symbol, StringComparison.OrdinalIgnoreCase)
|| "=".Equals(symbol, StringComparison.OrdinalIgnoreCase)
|| "<=".Equals(symbol, StringComparison.OrdinalIgnoreCase)
|| "<".Equals(symbol, StringComparison.OrdinalIgnoreCase)
)
{
//--------------------------------------------------------
// Begin, added by HC on 2016-12-14
// as requested by CQS users, add "IF" statement for GRI indicators
string exp = HandleIFCondition(table, i, companyID, fromDate, toDate, indicatorIDs, callerIndicatorID, callerAcceptedUnit, breakToMonthly, specifiedLocations, approvalStatus, usageDataSet, interval, indicatorIDsChain);
expression.Append(exp);
// End, added by HC on 2016-12-14
//--------------------------------------------------------
// Find End if, added by Alex Poon on 20190306
int ifIndex = i;
for (var j = ifIndex; j < count; j++)
{
string endIfSymbol = Convert.ToString(table.Rows[j][Common.Systems.Sustainability.Constants.IndicatorFormula.Symbol]);
if ("END IF".Equals(endIfSymbol, StringComparison.OrdinalIgnoreCase))
{
i = j;
break;
}
}
}
else
{
if (!string.IsNullOrWhiteSpace(symbol)
&& expression.Length > 0 // added by HC on 2016-06-24
)
{
if (i + 1 >= count && symbol != ")")
{
// ignore the symbol
}
else if (expression.ToString() != symbol)
{
expression.Append(symbol);
}
}
else if (expression.Length == 0 && symbol == "(")
{
expression.Append(symbol);
}
if (symbol == "days")
{
// added by HC on 2017-01-23, a new requirements for calculating average values by days.
if (fromDate != null && toDate != null)
{
int days = toDate.Value.Subtract(fromDate.Value).Days + 1;
expression.Append(days);
}
else
{
expression.Append(1);
}
}
} // end if ("IF".Equals(symbol, StringComparison.OrdinalIgnoreCase)...
if (expDic != null && expression != null)
{
expDic.Add(i, expression.ToString());
}
_sem.Release();
}), f);
taskList.Add(t);
if ("IF".Equals(formulaSymbol, StringComparison.OrdinalIgnoreCase))
{
for (var j = f; j < count; j++)
{
string endIfSymbol = Convert.ToString(table.Rows[j][Common.Systems.Sustainability.Constants.IndicatorFormula.Symbol]);
if ("END IF".Equals(endIfSymbol, StringComparison.OrdinalIgnoreCase))
{
f = j;
break;
}
}
}
}
Task.WaitAll(taskList.ToArray());
List<int> keys = expDic.Keys.ToList();
keys.Sort();
string finalExpression = "";
foreach (var key in keys)
{
finalExpression += expDic[key];
}
return finalExpression;
}
args in your case is data that will be passed to a delegate specified by Action<object> parameter.
See docs.
When using overload of StartNew with Action<object>, you need to supply next argument of type object, which will be used in passed delegate.
Task.Factory.StartNew((o) => {/* 1 will be used here */}, 1, token, options, scheduler);
MSDN
The args argument (referred to as "state" in the documentation) is a parameter you need to specify when you call to Task.Factory.StartNew.
state (Object): An object containing data to be used by the action delegate.
Sample:
object param = somevalue;
Task.Factory.StartNew( (arg) =>
{ /* get the arg value here.*/
}, param);

LINQ XML C# remove where condition in loop

Trying to delete nodes under certain conditions. Basically if certain checkboxes are checked I give an extra query with WHERE statement to my IENumerable named upit. After the queries has been set im trying to delete them iterating through every one, but nothing gets deleted everytime.
XDocument X = XDocument.Load(#"Financije.xml");
var upit = X.Element("POPIS").Elements("PODACI");
if (mjesec.Checked) { upit = upit.Where(E => (Convert.ToInt32(E.Element("MJESEC").Value) == Convert.ToInt32(mjesecbox.Text))); }
if (godina.Checked) { upit = upit.Where(E => (Convert.ToInt32(E.Element("GODINA").Value) == Convert.ToInt32(godinabox.Text))); }
if (ime.Checked) { upit = upit.Where(E => (E.Element("IME").Value.ToString().ToLower().Contains(search.Text.ToString().ToLower()))); }
if (opis.Checked) { upit = upit.Where(E => (E.Element("OPIS").Value.ToString().ToLower().Contains(search.Text.ToString().ToLower()))); }
if (veceod.Checked) { upit = upit.Where(E => (Convert.ToInt32(E.Element("CIJENA").Value.ToString()) > Convert.ToInt32(iznos.Text.ToString()))); }
if (manjeod.Checked) { upit = upit.Where(E => (Convert.ToInt32(E.Element("CIJENA").Value.ToString()) < Convert.ToInt32(iznos.Text.ToString()))); }
foreach (var item in upit)
{
upit.Remove();
}
and this is my XML file
<?xml version="1.0" encoding="utf-8"?>
<POPIS>
<PODACI>
<IME>test</IME>
<CIJENA>200</CIJENA>
<DATUM>12.1.2019</DATUM>
<MJESEC>1</MJESEC>
<GODINA>2019</GODINA>
<OPIS>test123333</OPIS>
</PODACI>
<PODACI>
<IME>voda</IME>
<CIJENA>230</CIJENA>
<DATUM>12.4.2018</DATUM>
<MJESEC>4</MJESEC>
<GODINA>2018</GODINA>
<OPIS>yes123no</OPIS>
</PODACI>
<PODACI>
<IME>oops</IME>
<OPIS>nice</OPIS>
<CIJENA>3</CIJENA>
<MJESEC>5</MJESEC>
<GODINA>2018<GODINA/>
<DATUM>24.02.2019</DATUM>
</PODACI>
<PODACI>
<IME>test</IME>
<OPIS>123</OPIS>
<CIJENA>1</CIJENA>
<MJESEC>12</MJESEC>
<GODINA>2019<GODINA/>
<DATUM>24.02.2019</DATUM>
</PODACI>
</POPIS>
It's a bit unclear what you want to end up with, but I assume you want to exclude items where they fail at least one case where the checkbox is checked and that comparison you are doing fails. So below achieves it in one query:
var X = XDocument.Load("Financije.xml");
var upit = X.Element("POPIS").Elements("PODACI");
var toRemove = upit.Where(u =>
// If mjesec is not checked, skip the predicate, otherwise evaluate it.
(!mjesec.Checked || (Convert.ToInt32(u.Element("MJESEC").Value) == Convert.ToInt32(mjesecbox.Text)))
// *And* do the same for godina and the rest of checkboxes...
&& (!godina.Checked || (Convert.ToInt32(u.Element("GODINA").Value) == Convert.ToInt32(godinabox.Text)))
&& (!ime.Checked || (u.Element("IME").Value.ToString().ToLower().Contains(search.Text.ToString().ToLower())))
&& (!opis.Checked || (u.Element("OPIS").Value.ToString().ToLower().Contains(search.Text.ToString().ToLower())))
&& (!veceod.Checked || (Convert.ToInt32(u.Element("CIJENA").Value.ToString()) > Convert.ToInt32(iznos.Text.ToString())))
&& (!manjeod.Checked || (Convert.ToInt32(u.Element("CIJENA").Value.ToString()) < Convert.ToInt32(iznos.Text.ToString()))));
X.Element("POPIS").ReplaceAll(upit.Except(toRemove));
X.Save("Financije.xml");
Give it a try
XDocument X = XDocument.Load(#"Financije.xml");
var upit = X.Element("POPIS").Elements("PODACI");
//I‘m only on phone so please excuse, if I take the wrong Type. Assign to null, to prevent Compiler-Error
IEnumerable<XElement> upitPart= null;
if (mjesec.Checked) { upitPart = upit.Where(E => (Convert.ToInt32(E.Element("MJESEC").Value) == Convert.ToInt32(mjesecbox.Text))); }
if (godina.Checked) { upitPart = upitPart.Where(E => (Convert.ToInt32(E.Element("GODINA").Value) == Convert.ToInt32(godinabox.Text))); }
if (ime.Checked) { upitPart = upitPart.Where(E => (E.Element("IME").Value.ToString().ToLower().Contains(search.Text.ToString().ToLower()))); }
if (opis.Checked) { upitPart = upitPart.Where(E => (E.Element("OPIS").Value.ToString().ToLower().Contains(search.Text.ToString().ToLower()))); }
if (veceod.Checked) { upitPart = upitPart.Where(E => (Convert.ToInt32(E.Element("CIJENA").Value.ToString()) > Convert.ToInt32(iznos.Text.ToString()))); }
if (manjeod.Checked) { upitPart = upitPart.Where(E => (Convert.ToInt32(E.Element("CIJENA").Value.ToString()) < Convert.ToInt32(iznos.Text.ToString()))); }
if(upitPart != null)
{
foreach (var item in upitPart)
{
upit.Remove(item);
}
}

Subtract from line and move to next

I want to subtract from the line with oldest date and where counter > 0, and when it reaches 0 I want to subtract from the next oldest line with the same itemId and do some other updates on other tables.
My question is if there is a better way to do it and if my code has no bad efficiency. If it breaks down, will the code do a rollback? Do I need try/catch? Please if any suggestions, provide with some code.
Here is my code:
public static int insertOrder(Order order)
{
using (var db = new AWarehouseDataClassesDataContext())
{
using (TransactionScope ts = new TransactionScope())
{
tblOrder row = generateOrderToBeInserted(order);
db.tblOrders.InsertOnSubmit(row);
db.SubmitChanges();
order.orderId = row.OrderId;
foreach(var x in order.insertList)
{
int qt = x.qty;
while (qt > 0)
{
var line = db.tblInsertLines.First(r => r.ItemId == x.itemId && r.Counter > 0);
int c = line.Counter;
for (int a = c; a > 0 && qt > 0; a--)
{
line.Counter = line.Counter - 1;
qt--;
}
db.SubmitChanges();
}
tblOrderLine orderLine = generateOrderLine(order, x);
db.tblOrderLines.InsertOnSubmit(orderLine);
db.SubmitChanges();
var item = db.tblItems.Single(i => i.ItemId == x.itemId);
item.Qty = item.Qty - x.qty;
item.LastUpdate = order.orderDate;
item.UpdatedBy = order.user;
db.SubmitChanges();
}
ts.Complete();
return order.orderId;
}
}
}

Convert if else to linq

I have following code in c# in which I am searching for lowest price flight .Now I want to convert it to Linq
for (; count < _flightSearchController.ListOfContracts.Count; count++)
{
contract = (DTContract)_flightSearchController.ListOfContracts[count];
if (contract.CurrentStatus == AvailabilityStatus.AVAILABLE)
{
if (CheckContractCitiesWithSearchCriteria(contract, originAirports, destinationAirports))
{
//if fare is lower than selected contract.
if (lowestPriceContract == null || lowestPriceContract.FareDetails.PriceForDefaultFlightSelection > contract.FareDetails.PriceForDefaultFlightSelection)
{
lowestPriceContract = contract;
}
else if (lowestPriceContract.FareDetails.PriceForDefaultFlightSelection == contract.FareDetails.PriceForDefaultFlightSelection)
{
if (lowestPriceContract.FareDetails.PriceAdult > 0 && (lowestPriceContract.FareDetails.PriceAdult + lowestPriceContract.FareDetails.FareTaxAdult) > (contract.FareDetails.PriceAdult + contract.FareDetails.FareTaxAdult))
{
lowestPriceContract = contract;
}
else if (lowestPriceContract.FareDetails.PriceSenior > 0 && (lowestPriceContract.FareDetails.PriceSenior + lowestPriceContract.FareDetails.FareTaxSenior) > (contract.FareDetails.PriceSenior + contract.FareDetails.FareTaxSenior))
{
lowestPriceContract = contract;
}
}
}
}
I tried it to convert but stuck in if else if section.
var q = _flightSearchController.ListOfContracts.ToList<DTContract>()
.Where(cont => cont.CurrentStatus == AvailabilityStatus.AVAILABLE);
if (lowestPriceContract == null || lowestPriceContract.FareDetails.PriceForDefaultFlightSelection > contract.FareDetails.PriceForDefaultFlightSelection)
{
}
Use the Min extension method:
var q = _flightSearchController.ListOfContracts
.Where(cont => cont.CurrentStatus == AvailabilityStatus.AVAILABLE
&& CheckContractCitiesWithSearchCriteria(cont, originAirports, destinationAirports))
.Min(cont=> cont.FareDetails.PriceForDefaultFlightSelection)
Edit I had glossed over the tie-breaker part, which makes it a bit more complicated. You can do it with sorting, but this will be slower when there are a lot of contracts:
var q = _flightSearchController.ListOfContracts
.Where(cont => cont.CurrentStatus == AvailabilityStatus.AVAILABLE)
&& CheckContractCitiesWithSearchCriteria(cont, originAirports, destinationAirports))
.OrderBy(cont => FareDetails.PriceForDefaultFlightSelection)
.ThenBy(cont => cont.FareDetails.PriceAdult + lowestPriceContract.FareDetails.FareTaxAdult)
.ThenBy(cont => cont.FareDetails.PriceSenior + lowestPriceContract.FareDetails.FareTaxSenior)
.First();
You could implement the IComparable interface for the FareDetails object to compare the prices, which would allow you to do this:
var q = _flightSearchController.ListOfContracts
.Where(cont => cont.CurrentStatus == AvailabilityStatus.AVAILABLE
&& CheckContractCitiesWithSearchCriteria(cont, originAirports, destinationAirports))
.Min(cont=> cont.FareDetails)

Separating Records into indvidual months for mvc

I have a collection of records. Which have two boxers, match date, location etc...
I want to separate them by months and group them together. Currently I have what is below. And it works to a degree. That looks for matchdates in the future. that is this year and steps through each month (1-12) and finds any matches in that date range.
Placing it into a nice dictionary of int, enumerable where int is the month and enumberable is the collection of matches in that month
//Build the matches list by Months!!!
var summarysDic = new Dictionary<int, IEnumerable<MatchSummary>>();
for (int i = 1; i <= 12; i++)
{
var MatchesOfMonth = matches.Where(x => x.MatchDate.Value.Year == DateTime.Now.Year &&
x.MatchDate.Value.Month == i &&
!x.HasResult() &&
x.MatchDate.Value > DateTime.Now);
if (MatchesOfMonth.Count() > 0)
{
summarysDic.Add(i, MatchesOfMonth.OrderBy(x => x.MatchDate).Select(x=> new MatchSummary(x)).ToArray());
}
}
Problem is this currently only deals with this year. I would like to instead make it so it works for "the next 6 months" but this would of course have to work over the new year as well!
Whats the best/cleanest way to go about doing this?
thanks in advance!
P.S on a side note i have yet to find how to simply do DateTime.Now.Month.add(1) for example (as i will always be going from current date forwards!)
-----COMPLETED CODE!-----
//Build the matches list by Months!!!
var summarysDic = new Dictionary<string, IEnumerable<MatchSummary>>();
for (int i = 1; i <= 12; i++)
{
var checkDate = DateTime.Now.AddMonths(i);
var MatchesOfMonth = matches.Where(x => x.MatchDate.Value.Month == checkDate.Month &&
x.MatchDate.Value.Year == checkDate.Year &&
!x.HasResult() &&
x.MatchDate.Value > DateTime.Now);
if (MatchesOfMonth.Count() > 0)
{
var firstMatchDate = MatchesOfMonth.First().MatchDate.Value;
if (firstMatchDate.Year != DateTime.Now.Year)
{
summarysDic.Add(firstMatchDate.ToString("MMMM yyyy"), MatchesOfMonth.OrderBy(x => x.MatchDate).Select(x => new MatchSummary(x)).ToArray());
}
else
{
summarysDic.Add(firstMatchDate.ToString("MMMM"), MatchesOfMonth.OrderBy(x => x.MatchDate).Select(x => new MatchSummary(x)).ToArray());
}
}
}
I believe you can get what you want without modifying your algorithm significantly:
//Build the matches list by Months!!!
var summarysDic = new Dictionary<int, IEnumerable<MatchSummary>>();
for (int i = 0; i <= 6; i++)
{
var checkDate = DateTime.Now.AddMonths(i);
var MatchesOfMonth = matches.Where(x => x.MatchDate.Value.Year == checkDate.Year &&
x.MatchDate.Value.Month == checkDate.Month &&
!x.HasResult() &&
x.MatchDate.Value > DateTime.Now);
if (MatchesOfMonth.Count() > 0)
{
summarysDic.Add(i, MatchesOfMonth.OrderBy(x => x.MatchDate).Select(x=> new MatchSummary(x)).ToArray());
}
}
What's wrong with DateTime.Now.AddMonth(1)?
var MatchesOfMonth = matches.Where(x => x.MatchDate.Value <= DateTime.Now.AddMonth(i)
&& !x.HasResult()
&& x.MatchDate.Value > DateTime.Now);
I haven't compiled that, but it should run with only fairly minor tweeking...

Categories