有条件的两个列表之间的 Linq

Duh*_*uha 2 c# linq

我有设置类

public class Setting 
{
    public virtual string Key { get; set; }
    public virtual string Value { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我必须列出

IEnumerable<Setting> A1 => contain {"A","1"}{"B","2"}
IEnumerable<Setting> A2 => contain {"A","1"}{"B","5"}
Run Code Online (Sandbox Code Playgroud)

我希望 linq 语句从列表 A2 中选择具有相同键和不同值的元素是 {"B","5"}

我试过了

A2.Where(x => A1.Any(y => y.Value != x.Value)).ToList();
Run Code Online (Sandbox Code Playgroud)

这给了我 A2 中的两个元素

任何人都可以帮助我谢谢


**编辑**我的设置类

 public class Setting : Entity<int>
{
    public virtual DateTime? ModificationDate { get; set; }
    public virtual string Name { get; set; }
    public virtual string Description { get; set; }
    public virtual string Key { get; set; }
    public virtual string Value { get; set; }
    public virtual string ModifiedBy { get; set; }
    public virtual string Type { get; set; }
    public virtual string ValidateRegex { get; set; }    
    public virtual bool IsSystem { get; set; }

}
Run Code Online (Sandbox Code Playgroud)

我已经从 mvc 返回 IEnumerable<Setting>让它命名设置,

然后我从数据库中获取原始设置,IEnumerable<Setting> 让它命名为 dbsettings

我想知道设置中更改的值以对其进行更新

Mar*_*kus 6

您还需要比较Key

A2.Where(x => A1.Any(y => y.Key == x.Key && y.Value != x.Value)).ToList();
Run Code Online (Sandbox Code Playgroud)

以下示例{ "B", "5" }作为结果返回:

void Main()
{
    var a1 = new List<Setting>(new Setting[] { 
        new Setting() { Key = "A", Value = "1" }, 
        new Setting() { Key = "B", Value = "2" } });
    var a2 = new List<Setting>(new Setting[] { 
        new Setting() { Key = "A", Value = "1" }, 
        new Setting() { Key = "B", Value = "5" } });
    var result = a2.Where(x => a1.Any(y => y.Key == x.Key && y.Value != x.Value)).ToList();
    Console.WriteLine(result);
}
Run Code Online (Sandbox Code Playgroud)

当您比较字符串时,您应该注意==!=分别总是区分大小写。因此,需要在两个列表中以相同的方式编写密钥(并且大小写的差异也将被识别为相关差异)。您还可以使用string.Compare的重载来更详细地指定比较选项。