Separating Records into indvidual months for mvc - c#

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...

Related

ASP.Net - Mvc5 : LINQ , Saving duplicate record problem

I am coding daily counter. Database Counter Table is empty. If someone is my first visitor of current day, then I am adding a record to database and i am setting counter=1; After this, when other visitor visit current day, then i am increasing my counter++ and i am updating the record.
So I my records must be like this:
Date:2018-10-01 counter:23
Date:2018-10-02 counter:65
Date:2018-10-03 counter:20
Date:2018-10-04 counter:89
My problem is this: If the site get visitor same time, linq save 2 record for same day. Like this:
Date:2018-10-01 counter:23
Date:2018-10-02 counter:1 //First record: counter=1
Date:2018-10-02 counter:65 //Second record: counter=65
Date:2018-10-03 counter:20
Date:2018-10-04 counter:1 //First record
Date:2018-10-04 counter:89 //second record
Date must be unique. How can I resolve this problem? My code is below. Thanks a lot.
public static int IncreaseCounter_DailySiteVisitors()
{
int counter = 0;
using (var context = new MyProjectEntities())
{
try
{
string format = "dd.MM.yyyy";
DateTime Today = DateTime.Now;
var obj = (from record in context.CounterDailySiteVisitor
where
record.DateRecord != null
&& record.DateRecord.HasValue
&& record.DateRecord.Value.Year == Today.Year
&& record.DateRecord.Value.Month == Today.Month
&& record.DateRecord.Value.Day == Today.Day
select record).FirstOrDefault();
//var obj = context.CounterDailyVisitor.Where(x => x.DateRecord != null && ((DateTime)x.DateRecord).ToString("yyyy.MM.dd") == DateTime.Now.ToString("yyyy.MM.dd")).FirstOrDefault();
if (obj != null)
{
counter = obj.Count ?? 0;
counter++;
obj.Count = counter;
context.SaveChanges();
}
else
{
var newRecordObj = context.CounterDailySiteVisitor.Create();
newRecordObj.Count = 1;
newRecordObj.DateRecord = Today;
context.CounterDailySiteVisitor.Add(newRecordObj);
context.SaveChanges();
}
}
catch (Exception e)
{
}
}
return counter;
}
the chances of this being hit by two thread at the same time is quite low.
but i guess technically it can so you would need to wrap this in a lock
Something like below...
public static int IncreaseCounter_DailySiteVisitors()
{
private readonly object somethingObject = new object();
var context = new MyProjectEntities()
var today = DateTime.Now;
var todaysRecord = context.CounterDailyVisitor
.SingleOrDefault(x => x.DateRecord.Year == Today.Year
&& x.DateRecord.Month == Today.Month
&& x.DateRecord.Day == Today.Day
);
if (todaysRecord != null)
{
//the existing count + 1
todaysRecord.Count = todaysRecord.Count++;
}
else
{
Lock(somethingObject)
{
//recheck
var todaysRecord = context.CounterDailyVisitor
.SingleOrDefault(x => x.DateRecord.Year == Today.Year
&& x.DateRecord.Month == Today.Month
&& x.DateRecord.Day == Today.Day
);
if (todaysRecord != null)
{
//the existing count + 1
todaysRecord.Count = todaysRecord.Count++;
}
else
{
var newRecordObj = new CounterDailyVisitor();
newRecordObj.Count = 1;
newRecordObj.DateRecord = DateTime.Now; //this shouldnt be nullable
context.CounterDailySiteVisitor.Add(newRecordObj);
}
}
}
context.SaveChanges();
}
This is quite a common concurrency problem i.e. race condition. You will either have to Lock around the code that reads and subsequently updates/inserts the value. Or you should call a stored procedure and have all the logic inside the stored proc.
Lock comes with it's own set of issues if you're planning on using a web farm or running multiple instances of this MVC app.

How can I simplify my nested for loops

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

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)

How would I optimize a nested for loop with linq [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
How would i write this with linq?
foreach (var to in allCurrentTradeObjects)
{
foreach (var ro in theseWantMe)
{
if (ro.Type != to.Type
|| ro.MaxRent < to.Rent
|| ro.MinRooms > to.Rooms
|| ro.MinSquareMeters > to.SquareMeters
|| ro.MaxPrice < to.Price
|| ro.MinFloors > to.Floors
|| ro.TradeObjectId == to.TradeObjectId
|| ro.TradeObjectId == myTradeObject.TradeObjectId)
{
continue;
}
RatingListTriangleModel rlt = new RatingListTriangleModel
{
To1Id = myTradeObject.TradeObjectId,
To2Id = to.TradeObjectId,
To3Id = ro.TradeObjectId,
T1OnT2Rating = 0,
T2OnT3Rating = 0,
T3OnT1Rating = 0,
TotalRating = 0
};
//_context.RatingListTriangle.Add(rlt);
this.InsertOrUpdate(rlt);
}
}
this.Save();
var query = from to in allCurrentTradeObjects
from ro in theseWantMe
where ro.Type == to.Type &&
ro.MaxRent >= to.Rent &&
ro.MinRooms <= to.Rooms &&
ro.MinSquareMeters <= to.SquareMeters &&
ro.MaxPrice >= to.Price &&
ro.MinFloors <= to.Floors &&
ro.TradeObjectId != to.TradeObjectId &&
ro.TradeObjectId != myTradeObject.TradeObjectId
select new RatingListTriangleModel
{
To1Id = myTradeObject.TradeObjectId,
To2Id = to.TradeObjectId,
To3Id = ro.TradeObjectId,
T1OnT2Rating = 0,
T2OnT3Rating = 0,
T3OnT1Rating = 0,
TotalRating = 0
};
foreach(var rlt in query)
this.InsertOrUpdate(rlt);
this.Save();
Start by converting the skeleton of the nested loops to LINQ:
var rtls = allCurrentTradeObjects
.SelectMany(to => theseWantMe.Select(ro => new {to, ro}));
This gives you a list of pairs {to, ro}. Now add filtering by inverting the continue condition:
var rtls = allCurrentTradeObjects
.SelectMany(to => theseWantMe.Select(ro => new {to, ro}));
.Where(p => p.ro.Type == p.to.Typpe && p.ro.MaxRent >= p.to.Rent && ...)
Finally, add a Select to call `new:
var rtls = allCurrentTradeObjects
.SelectMany(to => theseWantMe.Select(ro => new {to, ro}));
.Where(p => p.ro.Type == p.to.Typpe && p.ro.MaxRent >= p.to.Rent && ...)
.Select(p => new RatingListTriangleModel {
To1Id = myTradeObject.TradeObjectId,
To2Id = p.to.TradeObjectId,
To3Id = p.ro.TradeObjectId,
...
});
With rtls list in hand, you can call InsertOrUpdate in a loop.
Following is the method syntax.
allCurrentTradeObjects.Select (
to => to.theseWantMe.Where ( ro => !(ro.Type != to.Type
|| ro.MaxRent < to.Rent
|| ro.MinRooms > to.Rooms
|| ro.MinSquareMeters > to.SquareMeters
|| ro.MaxPrice < to.Price
|| ro.MinFloors > to.Floors
|| ro.TradeObjectId == to.TradeObjectId
|| ro.TradeObjectId == myTradeObject.TradeObjectId))
.Select({
var rlt = new RatingListTriangleModel
{
To1Id = myTradeObject.TradeObjectId,
To2Id = to.TradeObjectId,
To3Id = ro.TradeObjectId,
T1OnT2Rating = 0,
T2OnT3Rating = 0,
T3OnT1Rating = 0,
TotalRating = 0
};
this.InsertOrUpdate(rlt);
return rlt;
} ).ToArray();
this.Save();
There are many answers here advocating SelectMany (or double from). These are "optimize for readability" answers in that they do not change the N*M nested loop performance of this operation.
You shouldn't use that approach if both collections are large. Instead, you should take advantage of the well defined relationship between your two collections, and the hashing in Enumerable.Join to reduce the operation to N+M.
var myTradeObject = GetThatOneObject();
IEnumerable<RatingListTriangleModel> query =
from to in allCurrentTradeObjects
//pre-emptively filter to the interesting objects in the first collection
where to.TradeObjectId == myTradeObject.TradeObjectId
//take advantage of hashing in Enumerable.Join - theseWantMe is enumerated once
join ro in theseWantMe
on to.Type equals ro.Type
//remaining matching criteria
where to.Rent <= ro.MaxRent //rent is lower than max
&& ro.MinRooms <= to.Rooms //rooms are higher than min
&& ro.MinSquareMeters <= to.SquareMeters //area is higher than min
&& to.Price <= ro.MaxPrice //price is lower than max
&& ro.MinFloors <= to.Floors // floors are higher than min
&& to.TradeObjectId != ro.TradeObjectId //not same trade object
select CreateRatingListTriangleModel(myTradeObject, to, ro);
foreach(RatingListTriangleModel row in query)
{
this.InsertOrUpdate(row);
}
this.Save();
To increase readability I would start by refactoring the complicated condition and move it to a neat little function (It can also be a method of the object)
private bool IsMatchingTradeObject (TradeObject to, SomeOtherObject ro, int TradeObjectId)
{
return ro.Type == to.Type &&
ro.MaxRent >= to.Rent &&
ro.MinRooms <= to.Rooms &&
ro.MinSquareMeters <= to.SquareMeters &&
ro.MaxPrice >= to.Price &&
ro.MinFloors <= to.Floors &&
ro.TradeObjectId != to.TradeObjectId &&
ro.TradeObjectId != TradeObjectId;
}
Second I would do the same with the creation and initialization of the RatingListTriangleModel, i.e. move it to a small method and give it a meaningful name.
private RatingListTriangleModel CreateModel(TradeObject to, SomeOtherObject ro, int TradeObjectId)
{
return new RatingListTriangleModel
{
To1Id = myTradeObject.TradeObjectId,
To2Id = to.TradeObjectId,
To3Id = ro.TradeObjectId,
T1OnT2Rating = 0,
T2OnT3Rating = 0,
T3OnT1Rating = 0,
TotalRating = 0
};
The remaining code is much easier to read
foreach (var to in allCurrentTradeObjects)
foreach (var ro in theseWantMe)
if (IsMatchingTradeObject(to, ro, myTradeObject.TradeObjectId))
this.InsertOrUpdate(CreateModel(to, ro, myTradeObject.TradeObjectId));
this.Save();
Converting this to LINQ is easy:
allCurrentTradeObjects.Select (
to => to.Where (
ro => IsMatchingTradeObject (to, ro, myTradeObject.TradeObjectId)
)
).Select(
{
this.InsertOrUpdate(CreateModel(to, ro, myTradeObject.TradeObjectId));
return null;
}
);
this.Save();
However, the foreach-loops seem easier to read.

LINQ Entity Framework Select A Record

I have a trying to select a record.
In db, i have two records for Month 1 and 4.
I need to get values for both month 1 and 4, but all i get is value for month 1 both times in iteration (Month 1 and Month 4).
EX: In dB Month 1 Value is : 55 and Month 4 value is 22, but i get value 55 for both Months 1 and 4, while iteration in code.
for (var month = 1; month <= 12; month++)
{
var itemMonth = month;
var itemAuditReport = proxy.itemAuditReports.SingleOrDefault(i => i.SKU == itemSku && i.Month == itemMonth && i.Year==itemYear);
//
}
if (itemAuditReport == null)
{
// Do Something
}
Am i missing something ?
why dont you try out
I am guessing that itemAuditReportis the same item get assigned in iteration causing problem so make use of list and add items in it
List<Item> item = null;
for (var month = 1; month <= 12; month++)
{
var itemMonth = month;
var itemAuditReport = proxy.itemAuditReports.SingleOrDefault(i => i.SKU == itemSku &&
i.Month == itemMonth && i.Year==itemYear);
if(itemAuditReport!=null)
item.Add(itemAuditReport);
//
}
This will give you some insight on your error.
Why is it bad to use an iteration variable in a lambda expression
I will let you know if I find something to help you out fix the issue.
Like John Sykor suggested, try this:
for (var month = 1; month <= 12; month++)
{
var itemMonth = month;
var year = itemYear;
var sku = itemSku;
var itemAuditReport = proxy.itemAuditReports.SingleOrDefault(i =>
i.SKU == sku && i.Month == itemMonth && i.Year==year);
}
the following examples explain it more:
this outputs 10 ten times.
List<Action> actions = new List<Action>();
for (int i = 0; i < 10; i++)
{
actions.Add(() => Console.WriteLine(i));
}
foreach (Action action in actions)
{
action();
}
but the following outputs 0...9 as expected
List<Action> actions = new List<Action>();
for (int i = 0; i < 10; i++)
{
var x = i; //<--important line
actions.Add(() => Console.WriteLine(x));
}
foreach (Action action in actions)
{
action();
}
Yes, the keys in the Entity Framework model wasn't set properly, Sku was set as a primary key with title. in the model, hence bringing the same result set.
I changed the keys to be applied on Sku, Month and Year, and it worked great !!

Categories