How can I convert a SQL query like this:
Select *
from product
where c_id = 2
into a lambda expression?
I tried writing it like this:
db.Products.Where(x => x.c_id == 2).ToList()
Is this correct?
var filteredResult = db.Products.Where(x => x.c_id ==2 ).ToList();
should work, provided db.Products is collection.
Is this correct?
Yes
If you want to OrderBy along with Where, you can try this way
public ActionResult Index() {
return View(db.Products.Where(x => x.c_id == 2).OrderByDescending(x => x.pro_id).ToList());
}
Related
I have this query below and it returns a
IQueryable<IEnumerable<YogaSpaceEvent>>
but I want tit to return a List of YogaSpaceEvents
var listYogaEvents = dbContext.YogaProfiles.Select(i => i.YogaSpaceEvents.Where(j => j.EventStatus == YogaSpaceEventStatus.Active));
How do I get it to return a
List<YogaSpaceEvents>
Change the Select to SelectMany then call ToList like this:
List<YogaSpaceEvents> result =
dbContext.YogaProfiles
.SelectMany(i => i.YogaSpaceEvents.Where(j =>
j.EventStatus == YogaSpaceEventStatus.Active)).ToList();
This will collapse (flatten) all the nested IEnumerable<YogaSpaceEvent> and then accumulate the elements into a List instance.
And here is the line that is producing the error
var genreModel = storeDB.Categories.Include("Albums").ToPagedList(pageNumber, pageSize)
.Single(g => g.Name == Category);
What am i doing wrong here?
I infer that the ToPagedList uses skip and take internally.
Just include an orderBy before it, something like:
var genreModel = storeDB.Categories.Include("Albums").OrderBy(x=>x.Id).ToPagedList(pageNumber, pageSize) .Single(g => g.Name == Category);
I use this little piece of code to get the IDs I need, and put them in an array
var userids = from a in db.Person
select a.idlist;
string[] idarray = userids.FirstOrDefault().ToString().Split(';');
How can I use this array of ids to select the matching rows in another query like this
[HttpGet]
public ActionResult GetStuff()
{
var Item = from a in db.Table
where a.id == idarray[0]
and where a.id == idarray[1]
and where a.id == idarray[2]
etc...
select new
{
a.itemid,
a.Element
};
return Json(Item, JsonRequestBehavior.AllowGet);
}
Try something like this:
var Item = from a in db.Table
where idarray.Contains(a.id)
select new
{
a.itemid,
a.Element
};
var Item = from a in db.Table
where idarray.Contains(a.id)
select new
{
a.itemid,
a.Element
}.ToArray();
Don't you want to use Extension Method Lambda syntax? I is same Linq, but just has more code-like view:
var Item = db.Table.Where(x => x.Contains(a.id))
.Select(x => new
{
a.itemid,
a.Element
}).ToArray();
Here's what I usually do.
Get the IDs you need:
var ids = something.Where(s => s.SomeCondition).Select(s => s.Id);
Now Lets get the data based on the Ids:
var response = anothertable.Where(a => ids.Contains(a.Id);
You then can make it a list, array, or whatever you want to do with it. It will go through all the records in anothertable and find the records where the a.Id matches any of the ids.
I am in the process of learning Durandal and Breeze. And have choosing to create a SPA version of nerddinner.
The first query I need to execute is this:
public IEnumerable<JsonDinner> GetMostPopularDinners(int limit = 10)
{
var mostPopularDinners = from dinner in _db.Context.Dinners.Include("RSVPs")
where dinner.EventDate >= DateTime.Now
orderby dinner.RSVPs.Count descending
select dinner;
if (limit > 50 || limit <= 0)
limit = 10;
return mostPopularDinners.Take(limit).AsEnumerable().Select(JsonDinnerFromDinner);
}
I have started to write it with breeze but I am having trouble with this line " orderby dinner.RSVPs.Count descending" this is what I have so far.
var getMostPopularDinners = function() {
var query = EntityQuery
.from('dinners')
.where('eventDate', '>=', new Date(Date.now()))
.orderByDesc('RSVPs')
.expand('RSVPs');
Sorry, Breeze doesn't yet support ordering or filtering on an aggregate value ('count' in this case).
What you can do is turn this into a named query. (which is not well documented...) Basically this involves using the EntityQuery.withParameters method to pass additional parameters to any service method. So you can construct a query like the following that both passes parameters and still uses Breeze's IQueryable support.
EntityQuery.from("GetMostPopularDinners")
.withParameters({ EventDate: new Date(Date(now()) })
.take(10);
where your controller method would look something like this:
[HttpGet]
public IQueryable<Dinner> GetMostPopularDinners(DateTime eventDate) {
return _db.Context.Dinners.
.Where(dinner => dinner.EventDate >= eventDate)
.OrderByDescending(dinner => dinner.RSVPs.Count);
}
and ... you should not need to do an JsonDinnerFromDinner" call; Breeze handles this automatically.
A very new programmer to MVC, JSON & LINQ - I have created an ActionResult that returns a JSONResult:
var formhistory = from p in _formsRepository.ReturnedForms
where p.DateAdded >= DateTime.Now.Date.AddDays(-15) && p.DateAdded <= DateTime.Now.Date
group p by new {p.Centre, p.Form, p.DateAdded}
into g
select new {
g.Key.Centre,
g.Key.Form,
g.Key.DateAdded,
Total = g.Sum(p => p.Quantity)
};
return Json(formhistory, JsonRequestBehavior.AllowGet);
This gives me a nice JSON result set as follows:
[
{"Centre":"Centre1","Form":"Advice","DateAdded":"\/Date(1331856000000)\/","Total":1067},
{"Centre":"Centre1","Form":"Advice","DateAdded":"\/Date(1332460800000)\/","Total":808},
{"Centre":"Centre1","Form":"Advice","DateAdded":"\/Date(1333062000000)\/","Total":559},
{"Centre":"Centre1","Form":"Advice","DateAdded":"\/Date(1333666800000)\/","Total":1448}
]
My question is this: I'm trying to manipulate this JSON string so that instead of 2 key/value pairs for "Form" and "Total" I only have 1, i.e. "Form":"Total".
I realise this is probably a very basic question, but can anyone point me in the correct direction? (Apart from the door!)
select new {
g.Key.Centre,
//g.Key.Form,
g.Key.DateAdded,
Form = g.Sum(p => p.Quantity)
}
would give you a key "Form" whose value is the former "Total". Is that what you want?
Modify the select part in your linq query
select new {
g.Key.Centre,
g.Key.DateAdded,
NewField = String.Format("{0} - {1}",g.Key.Form,g.Sum(p => p.Quantity).ToString())
};
I think this will solve your purpose.