Converting a IQueryable IEnumerable entity to a list - asp.net-mvc

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.

Related

how to filter a list with condition in dart

I have a list and I want to put a condition on it. for example, I want to have items from list lst that value greater than 10:
var lst = [{"value":5 , "name":"test1"},
{"value":12 , "name":"test2"},
{"value":8 , "name":"test3"},
{"value":23 , "name":"test4"}];
/*
output: value greater than 10 =>
[{"value":12 , "name":"test2"},
{"value":23 , "name":"test4"}]
*/
You can either use the where function on iterables to filter its elements, then convert the resulting iterable back to a list, or use the list literal syntax, or a combination of the two where you "spread" the result of where:
var list = [ ... ];
var filtered1 = list.where((e) => e["value"] > 10).toList();
var filtered2 = [for (var e in list) if (e["value"] > 10) e];
var filtered3 = [... list.where((e) => e["value"] > 10)];
To filter a list base on a condition you can use List.where which takes a test function and returns a new Iterable that contains the elements that match the test.
To get a list with only the values greater than 10 you can filter you list of maps as such:
lst.where((e) => e['value'] > 10); //Returns a lazy Iterable
if you need to modify your list later you can append a .toList(), to get a new list.
try to use this code:
List lst = [{"value":5 , "name":"test1"} ,{"value":12 , "name":"test2"} , {"value":8 , "name":"test3"} , {"value":23 , "name":"test4"} ];
List newLst = lst.where( (o) => o['value'] > 5).toList();
print(newLst);
> Just try this Function, catogory_id == 1 is condition here
List<dynamic> chooseCatogory(List<dynamic> list) {
List newlist = list.where((o) => o['category_id'] == '1').toList();
return newlist;
}

Best Overloaded method match has some invalid arguments

I have two tables deal_outlet and vendors_outlet. I am trying to compare a list of outlet_id from deal_outlet table to vendor table but .contain method shows error has some invalid arguments. I really don't understand problem in this code.
public ActionResult Detail_of_deal(int id)
{
var d1 = db.deal_outlet.Where(x => x.outlet_id==id).ToList();
f_model.model4 = db.vendors_outlet.Where(x =>d1.Contains(x.outlet_id)).ToList();
var d = obj.detail_of_image(id,ref model);
return View(f_model);
}
Depending on the goal of the code you could try the following:
public ActionResult Detail_of_deal(int id)
{
var d1 = db.deal_outlet.Where(x => x.outlet_id==id).ToList();
f_model.model4 = db.vendors_outlet.AsEnumerable().Select(x => d1.Contains(x.outlet_id)).ToList();
var d = obj.detail_of_image(id,ref model);
return View(f_model);
}
That should make f_model.model4 a list of all the vendors_outlets that have a matching deal_outlet.id
The Linq Contains method returns true if the list contains the item passed in. You are asking to see if a list of deal_outlet objects contains an int, which obviously it won't.
Instead of projecting a collection of deal_outlets, project a list of integers:
var d1 = db.deal_outlet.Where(x => x.outlet_id==id).Select(x => x.outlet_id);
f_model.model4 = db.vendors_outlet.Where(x =>d1.Contains(x.outlet_id)).ToList();
But logically, that's the same as:
f_model.model4 = db.vendors_outlet.Where(x =>x.outlet_i==id)).ToList();
So it's not clear what you're trying to do.
EDIT
Based on your comments, I believe these are the queries you want:
i am trying to fetch list of outlet_id from deal_outlet table where deal_id equal to id,
var d1 = db.deal_outlet.Where(x => x.deal_id==id).ToList();
Now want to compare this list to vendor_outlet table and fetch those rows where outlet_id from deal_outlet table equals to outlet_id in vendor_outlet table
Get a list of ID's to match:
var ids = d1.Select(x => x.outlet_id).ToList();
And use Contains to see if the list contains any of the IDs from the related table:
f_model.model4 = db.vendors_outlet.Where(vo => ids.Contains(vo.outlet_id))
.ToList();

how to convert asquerable and igrouping to ienumrable

When I use this linq I am getting error
The model item passed into the dictionary is of type 'System.Linq.Enumerable+WhereSelectEnumerableIterator'2[System.Char,System.Char]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[groupBylinq.Models.employee]'.
This is my action
public ActionResult Index()
{
var result = from n in db.employees.Where(x => x.gender=="female")
.GroupBy(x => x.employee_sno).ToList() select n;
return View(result);
}
Result of GroupBy method is structure like [grouping_key, array[employee]]. But your view expect an array of employees. To achieve this you can do next
return View(result.SelectMany(v=>v).ToList());
But are you sure that you need GroupBy operator?

Entity Framework 4: Best practices in searching?

I am developing a ASP.NET MVC 3 Application with EF4. I have about 50,000 entities and I'm querying them through LINQ to find what matches best with the given search criteria. There are multiple search criterion (up to about 12) and these are matcheon a step by step basis.
Ex: 50,000 students
Get the students within the age range -> A
From A, get the students who are male -> B
From B, get students who are enrolled to course CS101 -> C
What's the best way to achieve this?
step by step doesn't mean a lot for SQL and your linq query will be transformed to sql to query the db...
so
//I'm a IQueryable
var queryableStudents =
students.Where(m =>
m.Age > 10 &&
m.Gender == 'm' &&
m.CourseList.Any(x => x.Name == 'CS101');
//I'm no more an IQueryable
var result = queryableStudents.ToList();//the query will be sent to db and result returned.
But if search criteria are optional, you can do
//I'm a IQueryable
var queryableStudents = students;
if (searchCriteria.Age > 0)
//I'm still a IQueryable
queryableStudents = queryableStudents.Where(m => m.Age => searchCriteria.Age);
if (!String.IsNullOrEmpty(searchCriteria.Gender))
//I'm still a IQueryable
queryableStudents = queryableStudents.Where(m => m.Gender == searchCriteria.Gender);
//Now I'm no more an IQueryable
var result = queryableStudents.ToList()//the query will be sent to db and result returned.
If you want a "REAL" step by step, (showing results for each step), you can do
//I'm not an IQueryable
var a= students.Where(m => m.Age > 10).ToList();//you will get all students from your db who respect your first criterion, and then work on an IEnumerable, not an IQueryable.
//I'm not IQueryable
var b= a.Where(m => m.Gender == 'm');
//I'm not an IQueryable
var c= b.Where(m => m.CourseList.Any(x => x.Name == "CS101");
var A = from s in students
where ((s.age < max) && (s.age > min))
select s;
var B = from a in A
where (a.gender.Equals("Male"))
select a;
var C = from b in B
where (b.EnrolledCourses().Contains("CS101"))
select b;
Answering my own question - after some thought I figured out the most effiecient way of doing this is to use something like ElasticSearch to index the entries I want.
The given use case is not a very good one for LINQ/C#.

Filtering Linq to Entity on Lazy Loading 3 levels Nested Query

Assuming a Entity Framework, in a LazyLoading context.
We have 3 entities:
Product(which has many Order Details)
OrderDetails(which has many Details)
Detail
The following query brings all Products with Name=Books. And to each of these products loads all the OrderDetails which OrderDetail.Quantity>5.
var query = anEntityManager.Products.Where(p => p.Name == "Books")
.Select(p => new { Product = p, OrderDetails = p.OrderDetails.Where(od => od.Quantity > 5) });
var results = query.ToList();
var products = results.Select( x => x.Product);
My Problem is that the Details of each OrderDetail are NOT being retrieved from DB. How can I make an Include in this query so Details are also loaded from DB in the same query?
I think you need to extend your projection:
var query = anEntityManager.Products.Where(p => p.Name == "Books")
.Select(p => new
{
Product = p,
OrderDetails = p.OrderDetails.Where(od => od.Quantity > 5),
Details = p.OrderDetails.Where(od => od.Quantity > 5)
.SelectMany(od => od.Details)
});
var results = query.ToList();
var products = results.Select( x => x.Product);
Using Include in a projection is not supported, so this (a bit ugly) code is the only way I know of to get the result in one database query.
You can probably also use Select instead of SelectMany (Details would then be an IEnumerable<IEnumerable<Detail>> instead of a flat IEnumerable<Detail>) because you are throwing away the projected properties anyway - except the Product property.

Resources