Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Linq查询问题_C#_Linq - Fatal编程技术网

C# Linq查询问题

C# Linq查询问题,c#,linq,C#,Linq,我有一个看起来像的DB,我需要一个查询,返回排序到列表中的所有类别,还应该返回与companyID匹配的任何类别 这是原始查询 var ROEBCategories = (from c in db.Content_Category select c).OrderBy(x => x.CategoryId).AsParallel().ToList(); 这是我尝试的查询 var roebCategories = (from c in db.Content_Category

我有一个看起来像的DB,我需要一个查询,返回排序到列表中的所有类别,还应该返回与companyID匹配的任何类别

这是原始查询

var ROEBCategories = (from c in db.Content_Category select c).OrderBy(x => x.CategoryId).AsParallel().ToList();
这是我尝试的查询

var roebCategories = (from c in db.Content_Category
                                      where c.CompanyId == rawData.CompanyId || (!(from c2 in db.Content_Category select c2.CategoryId).Contains(c.CategoryId) && (!c.CompanyId.HasValue))
                                      select c).OrderBy(x => x.CategoryId).AsParallel().ToList();

当前,原始查询返回全部15,新查询返回0。当categoryID不是15时,我希望新的返回14,但当categoryID是15时,我希望它返回最后一个类别

您的查询应该如下所示:

var roebCategories = db.Content_Category
                       .Where(c => c.CompanyId == null || c.CompanyId == rawData.CompanyId)
                       .OrderBy(x => x.CategoryId)
                       .ToList();
其中的第一部分匹配没有CompanyId的所有类别,第二部分匹配具有给定公司id的所有类别


因此,当rawData.CompanyId为15时,将获得所有15行。如果为null,则只会得到CompanyId为null的14行。

太棒了!这正是我想要/需要的。我很难编写linq查询,但这一条也很容易阅读