Linq两个列表之间有条件

时间:2015-12-10 09:20:22

标签: c# linq

我有设置类

public class Setting 
{
    public virtual string Key { get; set; }
    public virtual string Value { get; set; }
}

我必须列出

IEnumerable<Setting> A1 => contain {"A","1"}{"B","2"}
IEnumerable<Setting> A2 => contain {"A","1"}{"B","5"}

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

我试过

A2.Where(x => A1.Any(y => y.Value != x.Value)).ToList();

这给了我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; }

}

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

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

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

4 个答案:

答案 0 :(得分:4)

您还需要比较Key

A2.Where(x => A1.Any(y => y.Key == x.Key && y.Value != x.Value)).ToList();

以下示例返回{ "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);
}

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

答案 1 :(得分:3)

这应该这样做:

A2.Where(x => A1.Any(y => y.Key == x.Key && y.Value != x.Value))
顺便说一句,你的设置课似乎重新发明了轮子。 DictionaryTupleNameValueCollection都可以为您做到这一点。

答案 2 :(得分:2)

出于性能原因,您可以使用查找:

var a1KeyLookup = A1.ToLookup(x => x.Key);
List<Setting> a2List = A2
    .Where(a2 => a1KeyLookup[a2.Key].Any(a1 => a1.Value != a2.Value))
    .ToList();

以下是您的示例数据:

IEnumerable<Setting> A1 = new List<Setting> {
    new Setting{Key="A", Value="1"},
    new Setting{Key="B", Value="2"},
};
IEnumerable<Setting> A2 = new List<Setting> {
    new Setting{Key="A", Value="1"},
    new Setting{Key="B", Value="5"},
};

var a1KeyLookup = A1.ToLookup(x => x.Key);
List<Setting> a2List = A2
    .Where(a2 => a1KeyLookup[a2.Key].Any(a1 => a1.Value != a2.Value))
    .ToList();

按预期返回包含单个项目的列表:Key="B", Value="5"

答案 3 :(得分:2)

        var A1 = new List<Setting>(){new Setting(){Key = "A", Value = "1"}};
        var A2 = new List<Setting>() { new Setting() { Key = "A", Value = "2" } };
        var a1Keys = A1.Select(x => x.Key).ToList();
        var dupKeys = A2.Where(x => a1Keys.Contains(x.Key)).Select(x=>x.Key);
        var res = A2.Where(x => dupKeys.Contains(x.Key));