Answered by:
need help with linq to sql, and a navigation object

Question
-
User1034446946 posted
Hi
I have an entity model which has a navigation property to a list of another entity model
something like
ModelA
{
public List<ModelB> ModelB {get;set;}
}ModelB
{
public DateTime DateAdded {get;set;}
public string Name {get;set;}
}now ModelB can have anyhting in the name, however the important record is the newest
So i want to be able to select all ModelA's which have only the newest records in ModelB's has a name of "Foo".
I would normally use ModelA.Any(b => b.Name == foo).ToList()
however this will do all the records and not just the newest.
the date added will vary and some will have no records at all
Any help would be appriciated
Monday, February 12, 2018 11:49 AM
Answers
-
User1034446946 posted
I am thinking of using http://www.albahari.com/nutshell/predicatebuilder.aspx
but can find a tutorial that holds my hand enough
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Thursday, February 15, 2018 11:29 AM
All replies
-
User-166373564 posted
Hi,
We can use OrderByDescending and FirstOrDefault to get the newest record.
var m = new ModelA { ModelB = new List<ModelB> { new ModelB{ Name="foo", DateAdded=new DateTime(2012,1,1)}, new ModelB{ Name="foo", DateAdded=new DateTime(2013,1,1)}, new ModelB{ Name="foo", DateAdded=new DateTime(2018,1,1)}, } }; var list = m.ModelB.Where(b => b.Name == "foo").OrderByDescending(b => b.DateAdded).FirstOrDefault();
Regards,
Angie
Tuesday, February 13, 2018 6:37 AM -
User1034446946 posted
Thanks but that gives me a list of model b's and I want a list of modelA's
also name wouldn't always have foo in it,and I only want a ModelA if the newest record has a name of "foo"
how about
ModelA.Where(b => b.ModelB.OrderByDescending(o => t.DateAdded).FirstOrDefault().Name == "foo").FirstOrDefault();
would this work? (actually one issue i will have with this is i only allows me to seach one field and I need to search many)
Tuesday, February 13, 2018 1:28 PM -
User1034446946 posted
I am thinking of using http://www.albahari.com/nutshell/predicatebuilder.aspx
but can find a tutorial that holds my hand enough
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Thursday, February 15, 2018 11:29 AM