1

目前我有 2 个数据库表,如下所示:

---------------        --------------------
|  Categories |        |  Item_Categorys  |
---------------        --------------------
|      id     |        |        id        |
|     Title   |        |   Category_ID    |
---------------        |      Item_ID     |
                       --------------------

我有一个模型,它在我的视图上显示复选框,就像

LocalCategoryModel
-------------------
int categoryid
string category_title
bool ischecked

我正在尝试从表中获取所有项目类别,然后获取所有类别行,然后将它们交叉检查到如果有类别项目的位置,则将其放入 IEnumerable 中。所以最后,LocalCategory 拥有所有类别,然后 ischecked 设置为 true 或 false,具体取决于它在 Item_Categorys sql 表中是否有一行。

4

3 回答 3

1
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;
        }
于 2013-08-09T06:17:12.563 回答
0

我给你举个例子。

它可以帮助你。

我指的是一本名为“简而言之 C# 4.0”的书。


// 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 };

于 2013-08-09T05:24:35.083 回答
0
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
于 2013-08-09T06:22:14.520 回答