LINQ Entity Framework Select A Record - c#

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

Related

How to get the exact value list result using loop

this is my database which lists 5 results of the menu,
what i want is, if the date not equal to current Date (DateTime.Now), the result will be zero, like this:
Here is my code, on what I'm trying to do,
for (int i = 1; i <= DateTime.Now.ToShortDateString().Length; i++)
if (list.Any(x => x.Date.ToShortDateString() == i.ToString() ))
{
list.ToList().Add(new MenuModel
{
Total = list.First(x => x.Date.ToShortDateString() == i.ToString()).Total,
Location = list.First(x => x.Date.ToShortDateString() == i.ToString()).Location,
});
}
else
{
list.Add(new MenuModel
{
Total = list.First(x => x.Date.ToShortDateString() != i.ToString()).Total=0,
Location = list.First(x => x.Date.ToShortDateString() != i.ToString()).Location,
});
}
but the result that i get is like this,
The location, didnt show the real value, which will be A,B,C,D and E.. How to get the exact value of location?
What you really need is little linq magic. The below linq Get the Total based on the current date to actual value and if not to current date then set to 0.
DateTime date = DateTime.Today;
var menus = list.Select(l => new MenuModel
{
Total = l.Date.Date == date ? l.Total : 0,
Location = l.Location,
});

Compare when a Variable becomes bigger than a Value in List/IEnumerable

Background/Context
I am currently building a function that will take a value and compare it against a list to find at which point the string values become bigger. The value I take is a date and the String contains a range of dates that are headings to a chart and essentially I am trying to find the column in excel where this date would fit in. The heading dates are all weekly dates. I've tried to get my logic around it but nothing seems to be working so thought I'd ask on here.
Logic Behind Code
The program creates a IEnumerable to find cell of records for which date we are looking up
The program creates a IEnumerable with all the dates in the headings.
The program takes that date and compares it to the IEnumerable in 2. to return a column where the new date will go.
Code up to point 2
List<string> Sheet1Rows = new List<string>();
List<string> Sheet2Rows = new List<string>();
List<DateTime> ColumnDates = new List<DateTime>();
//List<int> NewRowsNumber = new List<int>();
for (int row = 9; row <= LastRowSheet1; row++)
{
Sheet1Rows.Add(ExcelWksht1.Cells[row, 1].Value);
}
for (int row = 9; row <= LastRowSheet2; row++)
{
Sheet2Rows.Add(ExcelWksht2.Cells[row, 1].Value);
}
for (int column = 16; column <= LastColumnSheet2; column++)
{
ColumnDates.Add(ExcelWksht2.Cells[5, column].Value);
}
IEnumerable<string> Names1 = Sheet1Rows;
IEnumerable<string> Names2 = Sheet2Rows;
IEnumerable<DateTime> Dates1 = ColumnDates;
IEnumerable<string> NamesInBoth = Names1.Intersect(Names2);
IEnumerable<string> NamesOnlyInTwo = Names2.Except(Names1);
Debug.Print("NamesInBoth\n==========");
foreach (var n in NamesInBoth)
{
Debug.Print(n.ToString());
//Get Row Values
int rowinsheet1 = (Sheet1Rows.FindIndex(x => String.Compare(x, n) == 0)) + 9;
int rowinsheet2 = (Sheet2Rows.FindIndex(x => String.Compare(x, n) == 0)) + 9;
//Get Date Values
var Sheet1Date = ExcelWksht1.Cells[rowinsheet1, 9].Value.ToString();
var Sheet2Date = ExcelWksht2.Cells[rowinsheet2, 9].Value.ToString();
if (Sheet1Date != "No Planned Date" && Sheet2Date != "No Planned Date")
{
if (Sheet1Date != null && Sheet2Date != null)
{
if (Sheet1Date.ToString() != Sheet2Date.ToString())
{
//THIS IS WHERE IM STRUGGLING
}
}
else
{
((Excel.Range)ExcelWksht2.Cells[rowinsheet2, 1]).EntireRow.Interior.Color = Microsoft.Office.Interop.Excel.XlRgbColor.rgbOrange;
}
}
}
The Problem
As shown in the code I need to figure out a way to construct a loop (?) to check the row date value against all the heading values in the IEnumerable to give me the date value that begins the 7 day range.

C# change object's order and order of all siblings in same category

I work on mini CMS with objects that have the parameter ORDER (int). Suppose I have 10 objects and each has its own ORDER from 1 to 10.
I want to move the 3rd element to the 8th position hence the 3 element should get the position (order) 8 and the 8 element is set to become 7 and 7-6 and 6-5 and so to 1 .....
And vice versa: if I move the 8 element to the 2 position, then the 8 element gets the order 2 2 gets 3, 3 gets 4 and so before the query.Coun
I wrote a crooked code which, when loaded, is buggy and produces a different result than I would like. Can anyone encountered such a problem educate ..
Sorry for my english here is my code:
public static void UpdateJsTreeOrder(this IDocumentSession session, string pageId, string parent, string element)
{
var pages = session.Query<Page>().Where(x => x.ParentPageId == parent);
var orderList = pages.Select(x => x.Order).Take(1024).ToList();
var page = session.Load<Page>(pageId);
if (element == null)
{
var subList = pages.Where(x => x.Order != page.Order).Take(1024).ToList();
foreach (var item in subList)
{
item.Order++;
session.Store(item);
}
page.Order = 1;
session.Store(page);
return;
}
var newOrder = session.Load<Page>(element).Order;
if (!orderList.Any())
{
//its the first item
}
//last item
if (newOrder == orderList.Max())
{
var subList = pages.Where(x => x.Order <= newOrder && x.Order != page.Order).Take(1024).ToList();
foreach (var item in subList)
{
item.Order--;
session.Store(item);
}
}
//first item
else if (newOrder == orderList.Min())
{
var subList = pages;
foreach (var item in subList)
{
item.Order--;
session.Store(item);
}
}
//int the middle
else
{
var subList = pages.Where(x => x.Order >= newOrder || x.Order == newOrder).Take(1024).ToList();
foreach (var item in subList)
{
item.Order--;
session.Store(item);
}
}
page.Order = newOrder;
session.Store(page);
}
If you are working LINQ (seems like you are) and have a collection you can manipulate, the following might work for you:
int oldOrder = 8;
int newOrder = 3;
if (newOrder < oldOrder) {
SmallBit moving = collection.Where(c => c.Order == oldOrder).First();
collection.Where(c => c.Order >= newOrder && c.Order < oldOrder).ToList().ForEach(c => c.Order += 1);
moving.Order = newOrder;
} else {
SmallBit moving = collection.Where(c => c.Order == oldOrder).First();
collection.Where(c => c.Order > oldOrder && c.Order <= newOrder).ToList().ForEach(c => c.Order -= 1);
moving.Order = newOrder;
}
Edit: SmallBit in this case is simply the page object - I had renamed it in my fiddle.
I believe you can get desired result using Insert and RemoveAt Statement Like this
public static void UpdateJsTreeOrder(int from,int to)
{
var pages = new List<int>() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
var item = pages.ElementAt(from);
pages.RemoveAt(from);
pages.Insert(to,item);
}
This is just an example you can incorporate in your code
Ok, so there's three (valid) cases...
Item doesn't move
Item moves to a larger Order, decrease the other items to make room.
Item moves to a smaller Order, increase the other items to make room.
So, to address each case:
private void MoveItem(List<Page> source, int fromOrder, int toOrder)
{
if (fromOrder == toOrder)
{ return; }
if (fromOrder < toOrder)
{
foreach(Page page in source)
{
bool match = page.Order == fromOrder;
bool between = fromOrder < page.Order && page.Order <= toOrder;
page.Order = match ? toOrder :
between ? page.Order - 1 :
page.Order;
}
}
else
{
foreach(Page page in source)
{
bool match = page.Order == fromOrder;
bool between = toOrder <= page.Order && page.Order < fromOrder;
page.Order = match ? toOrder :
between ? page.Order + 1 :
page.Order;
}
}
}

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

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