首页 > 解决方案 > WHERE 子句中的条件语句

问题描述

考虑以下记录: 记录

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

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,则选择此记录),如果没有,则检查是否存在此 ID 且 ConfigurationName 等于 customName 的记录(如果为 true,则选择此游戏对象),如果不采用此 ID 的记录,其中 ConfigurationName 为空。

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

标签: c#linq

解决方案


似乎您已经有了一个工作概念,只需添加draftName与您的Where状况的比较即可。

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

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

编辑#1:

这应该反映 OP 想要什么。

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

然后剩下的:

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 to 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();

推荐阅读