我有三张桌子:
1-表Car_Types
_____________________
| Id | Name |
|____________________|
| 1 | Pickup |
| 2 | Sedan |
| 3 | Minivan |
| 4 | SUV |
|____________________|
2 - 表Car_Options
_________________________________________________
| Id | Car_Type_Id | Company_Id |
_________________________________________________|
| 1 | 1 | Null |
| 2 | 2 | Null |
| 3 | 3 | Null |
| 4 | 4 | Null |
| 5 | 1 | 1 |
| 6 | 2 | 1 |
|________________________________________________|
3 - 表公司类似于表car_types
所以我想选择使用linq
所有car_options
,事情是:查询有Company_Id X
所以我想所有car_options
(4)与Company_Id == X
但如果没有car_option
惠特company_id == x
为其中一个car_type_ids
然后我想要那car_option
与car_type_id
和company_id==null
。我认为我需要的是加入,但我不知道该怎么做。
因此,如果company_id为1,我想要的结果将是:
_________________________________________________
| Id | Car_Type_Id | Company_Id |
_________________________________________________|
| 5 | 1 | 1 |
| 6 | 2 | 1 |
| 3 | 3 | Null |
| 4 | 4 | Null |
|________________________________________________|
你的问题有点令人费解 - 但让我们从这里开始吧。
您想要查找具有company_ID x的所有内容,以便从简单的linq查询开始:
car_options.Where(c => c.Company_Id == X);
然后你想要抓住任何没有Company_Id但是有一个与x匹配的car_type_id ...所以添加到你的查询
car_options.Where(c => c.Company_Id == X || (c.Company_Id == null && c.car_type_id == x))
然后,您只想获取匹配的公司ID(如果存在)。因此,按公司ID对它们进行分组,按照companyID对这些组进行排序,因此如果有那些具有(非空)公司ID的组,则它们将是第一个(否则只有一个组 - null公司ID)
car_options.Where(c => c.Company_Id == X || (c.Company_Id == null && c.car_type_id == x))
.GroupBy(c => c.Company_ID)
.OrderByDescending(g => g.Key)
.FirstOrDefault();
这将返回一个IGrouping,你可以使用它与IEnumerable相同(它只有一个键,如果你想检查你是否正在查看空公司ID或匹配x的那个,这可能很方便。
根据更明确的要求进行编辑:
car_options.GroupBy(c => c.car_type_id)
.Select(g => g.Where(c => c.Company_ID == X || c.Company_Id == null)
.OrderByDescending(c => c.Company_ID)
.FirstOrDefault());