I have list of items contained in viewbag ViewBag.RoomBookings
As an example:
I want all the Roombookings with ViewBag.RoomBookings.RoomNo = 6 AND ViewBag.RoomBookings.Time < DateTime.Now AND ViewBag.RoomBookings.Time < DateTime.Now + 3600
Looping through is a NO.
And it must be done on the view, as I also need access to all the other roombookings too to populate a timetable.
Alternatively, Im thinking of Hash lists? Where I could list it with RoomNo, and Time and access it that way. But I cant find any good documentation on this if its even possible.
Ive tried a few things (just to test a method that works (these wont follow the same critera as above)):
var RoomBookingsTemp = ViewBag.RoomBookings;
var newlist = (from RoomOcc in RoomBookingsTemp where RoomOcc.EndDateTime < DateTime.Now select RoomOcc.RoomNo);
var bookings = RoomBookingsTemp.Where(roombooking => DateCheckStart < roombooking.EndDateTime && DateCheckEnd > roombooking.StartDateTime && roombooking.RoomNo == RoomNo);
var newlist = RoomBookingsTemp.Select(m => m["RentalNo"]);
But none are valid.
You need to cast the RoomBookingsTemp variable. When you declare it directly from the ViewBag it's still a dynamic type [details about viewbag] and the error your seeing is that linq can't query/iterate over a dynamic type.
I'm not sure what type you're actually using but try something like this...
var RoomBookingsTemp = ViewBag.RoomBookings as List<RoomBooking>;
or
List<RoomBooking> RoomBookingsTemp = ViewBag.RoomBookings;
What's wrong with your second method? You are just missing the select.
// Some statements removed from where for clarity
var bookings = RoomBookingsTemp.Where(rb => rb.RoomNo == 6).Select(rb => rb);
Related
I tried to compare two ids and get some result.it works for other strings.but not for this.
I tried like this.
var neededData = mainFaires.Where(c => c.trimacid == passId );
in here passId= OX20160330HAVHAV
and in the mainFaires list, in somewhere it includes this id.but it didn't give the result.I found in here
var x = mainFaires.ElementAt(27261);
this list include the same id.but didn't give result.I can't think why.
ElementAt is find the position.
You should use select to find the records
var x = mainFaires.Select(o => o.trimacid == 27261);
You should use .ToList() .First() or .FirstOrDefault() to actually commit the query and get a result. Your code only defined the query, but didn't actually submit it to the data collection.
If you expect only one item as a result, you're code should look like this:
var neededData = mainFaires.Where(c => c.trimacid == passId ).FirstOrDefault();
If there was no item found, neededData would be NULL or whatever the default value is. You may also check the Documentation here https://msdn.microsoft.com/en-us/library/system.linq.enumerable%28v=vs.100%29.aspx
I'm querying a list of objects, and I want to return a TimeSpan's ticks list of the difference between the time registered in the object, and now.
I wanted all in one expression, so:
var list = (from r in res where r.Site == "CNIS"
select Math.Abs((r.Timestamp.Value - DateTime.Now).Ticks)).ToList();
But I get the following error:
Exception Details: DbArithmeticExpression arguments must have a numeric common type
I already managed to do a workaround. For example, my code looks like this now:
var list = new List<long>();
foreach(var item in (from r in res where r.Site == "CNIS" select r))
list.Add(Math.Abs((item.Timestamp.Value - DateTime.Now).Ticks));
But what I really wanted to know is if it is possible to get the Timespan diff from a DateTime value to now, in a single LINQ query
It seems the error is relevant to the translation of your select statement into SQL.If fecthing the results form DB is not a problem you can do it using AsEnumerable and then project the items:
var now = DateTime.Now;
var list = res.Where(r => r.Site == "CNIS")
.AsEnumerable()
.Select(x => Math.Abs((x.Timestamp.Value - now).Ticks))
.ToList();
And since the value of DateTime.Now changes you should probably store the it into a variable and use it in the calculation.
I have a List/ICollection from a database query and I want to filter it by date - something like
// razor syntax
var results = db.Query(fooBars).ToList();
var overdue = results.Where( x => x.Date < DateTime.Now );
This is throwing an error
CS1502: The best overloaded method match for 'System.Web.WebPages.WebPageExecutingBase.Write(System.Web.WebPages.HelperResult)' has some invalid arguments
Any ideas how I might implement this?
Thanks in advance.
PS: I don't mean to confuse the issue but I am under the impression that saving the results in an object and working on that to populate the HTML page is a better approach than querying the database multiple times. Is that correct? e.g.
// #1.
db.Query("SELECT this FROM that WHERE Date < CAST(GetDate() as Date)");
// versus
results.Where( x => x.Date < DateTime.Now ) // doesn't work but you get the idea :-)
// #2
db.Quer("SELECT count(this) FROM that WHERE status = 'COMPLETE'")
// versus
results.Select( x => x.status = "COMPLETE" ).Count
Cheers.
I realized that for some odd reason you can't chain the .Where() after the .Select(), so I came up with this.
var eventCalendar = db.EventCalendars.Where(q => q.Date == e.Day.Date);
if (!isLogged)
{
eventCalendar = eventCalendar.Where(q => q.ClientFlag == true);
}
eventCalendar = eventCalendar.Select(q => q.EnvironmentId).Distinct();
but now I get and error at the .Select
"Cannot implicitly convert type 'System.Linq.IQueryable<short>' to 'System.Linq.IQueryable<IT_Portal.EventCalendar>'. An explicit conversion exists (are you missing a cast?)"
What am I doing wrong? To put it simply, I just want to be able to grab Distinct Environment ID from the Calendar Event table so that I can notify users if there is an event occurring that day on a specific environment. Finally if the user is not logged in, get only Environment Id from events that are marked to be displayed for client (ClientFlag).
Your last line is the problem. You're trying to re-use a local variable that is a different type than you're assigning to it. You just need to change it slightly:
var eventCalendarEnvironmentIds =
eventCalendar.Select(q => q.EnvironmentId).Distinct();
You need a new variable.
var environmentIDs = eventCalendar.Select(q => q.EnvironmentId).Distinct();
By selecting Select(q => q.EnvironmentId) you are actually selecting the EnvironmentId and not the eventCalenderObject.
Try changing:
var eventCalendar = db.EventCalendars.Where(q => q.Date == e.Day.Date);
to:
// I specify IQueryable, you can use 'var' - you simply need to change the variable name
IQueryable eventQuery = db.EventCalendars.Where(q => q.Date == e.Day.Date);
Then, selecting:
var eventCalendar = eventQuery.Select(q => q.EnvironmentId).Distinct();
Sometimes, when you continue to use var, you may lose sight of the data type. You should use the actual data type as often as you can. Getting caught in the trap of using var is not a good practice, IMO.
Has anyone had problems gettting associations to load using LINQ to SQL when your child record was loaded via a lambda query? For example:
var orderLine = db.OrderLines.
Where(ol => ol.ID == orderLineID select ol).
First();
// navigate to order via the association
var order = orderLine.GetOrder();
What I get basically is a null result from GetOrder().
But if I do this instead:
var orderLine = (from ol in db.OrderLines where ol.ID == orderLineID).First();
var order = orderLine.GetOrder();
Works fine.
What can cause this? Is this a bug?
EDIT: Here's the actual code that WORKS with the Lambda expression commented out that DOESN'T WORK
var msg = db.Messages.Where(m => m.ID == msgID).First();
if (msg.SentTS.HasValue) return;
// Get the message recipients
// I don't get it.. why doesn't lambda expressions work here? returns 0 results!
// var testtos = msg.GetMessageTos.Where(mt => mt.Active);
var tos = from mt in db.MessagesTos
where mt.Active && mt.MessageID == msgID
select mt;
You can also try this, I think it's a little cleaner.
var orderLine = db.OrderLines.Single( ol => ol.ID == orderLineID );
var order = orderLine.GetOrder();
I beileive in your non-working example you want to use .First() instead of .Single().
It seems to me that the problem has more to do with the association than lambda expressions.
In your scenario, this should work:
var tos = db.MessagesTos.Where(mt=> mt.Active && mt.MessageID);
while this won't:
var tos = from mt in msg.SentTS
where mt.Active
select mt;
As to why it doesn't work, I suggest taking a look at the association in the designer and checking its matching the db model correctly (matching the correct columns). I also suggest to confirm that msg.SentTS is effectively coming empty, regardless of any further query you run on it.
See my EDIT for the code that works. I guess sometimes the "Answer" is to do what works, not necessarily what you understand.