繁体   English   中英

WHERE 子句中的条件语句

[英]Conditional statement inside WHERE clause

考虑以下记录:记录

概述的记录是相同的游戏对象,但它们具有不同的配置名称(ConfigurationName 为 null 的记录是我原始表的副本)。

string customName= "Config1";

string draftName = "Draft_" + id;

   var list = db.JoinedGameObjects
                            .Where(x => x.TBUploads_ID == id)
                            .Where(x => x.ConfigurationName.Equals(customName) || x.ConfigurationName == null)
                            .Select(x => new GameObjectViewModel()
                            {
                                ID = x.ID,
                                GameObjectName = x.GameObjectName,
                                Category = x.Category,
                                Family = x.Family,
                                Type = x.Type,
                                MetaTypeJson = x.MetaTypeJson,
                                MaterialsJson = x.MaterialsJson,
                                MetadataVisibilityJson = x.MetadataVisibilityJson,
                                Visible = x.joined_Visible ?? x.Visible
                            }).ToList();

此代码获取 ConfigurationName 等于我的 customName 变量或 ConfigurationName = null 的所有记录。 然而,这不是我想要的。

我将尝试用一个例子来解释预期的结果。

我首先要检查是否有此 ID 的 ConfigurationName 等于 DraftName 的记录(如果为 true select 此记录),如果不检查是否有此 ID 的记录 ConfigurationName 等于 customName(如果为 true select 此游戏对象),如果不使用此 ID 记录 ConfigurationName 为 null。

有人可以指导我正确的方向或提供一个可行的例子吗?

似乎您已经有了一个可行的概念,只需在您的Where条件中添加一个draftName比较。

它将按照Where中定义的顺序应用条件

.Where(x => x.ConfigurationName.Equals(draftName) || x.ConfigurationName.Equals(customName) || x.ConfigurationName == null)

编辑#1:

这应该反映 OP 想要什么。

为了简洁起见,我使用了自定义的 `Person` class 并简化了代码示例,所以概念应该很容易理解:
 public class Person { public int Id { get; set; } public string Name { get; set; } }

然后是 rest:

 var people = new List<Person> { new Person {Id= 1, Name = null}, new Person {Id= 1, Name = "Mike"}, new Person {Id= 1, Name = "John"}, new Person{Id = 2, Name= null}, new Person{Id = 2, Name= "Peter"}, }; //filter values string filter1 = "Mike"; string filter2 = "John"; string filter3 = null; var byPriority = people.Where(p=> p.Name == filter1 || p.Name == filter2 || p.Name == filter3).OrderByDescending(p => p.Name == filter1).ThenByDescending(p => p.Name == filter2).ThenByDescending(p => p.Name == filter3); var oneByIId = byPriority.GroupBy(p => p.Id).Select(g => g.First()).ToList();

这里的关键是按条件优先级对记录进行排序。 然后将记录分组并从每组中取出第一个

编辑#2

在某些情况下,LINQ 到 SQL 与 `NULL` 比较时可能会失败,在这种情况下,修改 null 比较零件如下:
 var byPriority = people.Where(p=> p.Name == filter1 || p.Name == filter2 || object.Equals(p.Name,filter3)).OrderByDescending(p => p.Name == filter1).ThenByDescending(p => p.Name == filter2).ThenByDescending(p => object.Equals(p.Name,filter3)); var oneByIId = byPriority.GroupBy(p => p.Id).Select(g => g.First()).ToList();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM