Reputation: 1080
Currently I have 2 database tables which looks like:
--------------- --------------------
| Categories | | Item_Categorys |
--------------- --------------------
| id | | id |
| Title | | Category_ID |
--------------- | Item_ID |
--------------------
I have a Model which displays Checkboxes on my View which is like
LocalCategoryModel
-------------------
int categoryid
string category_title
bool ischecked
I'm trying to get all the items categorys from the table and then get all the category rows then crosscheck them to where if there's a category item, it Puts it in a IEnumerable. So at the end, the LocalCategory has all the categories and then the ischecked is set to true or false depending on if it has a row in the Item_Categorys sql table.
Upvotes: 1
Views: 3557
Reputation: 117445
class Category { public int id; public string Title; };
class CategoryItem { public int category_id; public int item_id; }
class Category { public int id; public string title; };
// Create categories list
var categories = new List<Category>() { new Category { id = 1, title = "First" }, new Category { id = 2, title = "Second" } };
// Create categories items list
var categories_items = new List<CategoryItem>() { new CategoryItem { category_id = 1, item_id = 2 } };
// All categories in categories_items
var categories_items_set = categories_items.Select(x => x.category_id).Distinct();
// Final query
var q = categories.Select(x => new { categoryid = x.id, category_title = x.title, ischecked = categories_items_set.Contains(x.id) });
q.ToList()
// output
categoryid = 1, category_title = First, ischecked = True
categoryid = 2, category_title = Second, ischecked = False
Upvotes: 0
Reputation: 12709
public class LocalCategoryModel
{
public int categoryid { get; set; }
public string category_title { get; set; }
public bool ischecked { get; set; }
}
public IEnumerable<LocalCategoryModel> getSourec()
{
IEnumerable<LocalCategoryModel> query = from tbcat in Categories
join tbitem_cat in dc.Item_Categorys
on tbcat.id equals tbitem_cat.Category_ID into ct
from tbitem_cat in ct.DefaultIfEmpty()
select new LocalCategoryModel
{
categoryid = tbcat.id,
category_title = tbcat.Title,
ischecked = tbitem_cat == null ? false : true
};
return query;
}
Upvotes: 1
Reputation: 49
I'll get you some example.
It helps you.
I refer to a book named 'C# 4.0 IN A NUTSHELL'.
// outer collection
customers.Join (
purchases, // inner collection
c => c.ID, // outer key selector
p => p.CustomerID, // inner key selector
(c, p) => new { c, p } ) // result selector
.OrderBy (x => x.p.Price)
.Select (x => x.c.Name + " bought a " + x.p.Description);
from c in customers
join p in purchases on c.ID equals p.CustomerID
select new { c.Name, p.Description, p.Price };
Upvotes: 0