【问题标题】:How do i get the difference in two lists in C#?如何在 C# 中获得两个列表的区别?
【发布时间】:2012-03-23 14:03:15
【问题描述】:

好的,所以我在 C# 中有两个列表

List<Attribute> attributes = new List<Attribute>();
List<string> songs = new List<string>();

一个是字符串,一个是我创建的属性对象..非常简单

class Attribute
{
    public string size { get; set; }
    public string link { get; set; }
    public string name { get; set; }
    public Attribute(){}
    public Attribute(string s, string l, string n) 
    {
        size = s;
        link = l;
        name = n;
    }
}

我现在必须比较看看哪些歌曲不在属性名称中,例如

songs.Add("something"); 
songs.Add("another"); 
songs.Add("yet another");

Attribute a = new Attribute("500", "http://google.com", "something" ); 
attributes.Add(a);

我想要一种返回“另一个”和“又一个”的方法,因为它们不在属性列表名称中

所以对于伪代码

difference = songs - attributes.names

【问题讨论】:

    标签: c# linq list linq-to-objects


    【解决方案1】:
    var difference = songs.Except(attributes.Select(s=>s.name)).ToList();
    

    编辑

    添加 ToList() 使其成为列表

    【讨论】:

    • 一个可枚举的。如果需要,请使用 ToList()。
    • 对不起阿德里安,打败我了。这实际上是一个非常好的答案,我自己一直想知道如何实现这一点。 +1
    【解决方案2】:

    值得指出的是,此处发布的答案将返回attributes.names 中不存在的songs 列表,但不会为您提供songs 中不存在的attributes.names 列表。

    虽然这是 OP 想要的,但标题可能有点误导,特别是如果(像我一样)你来这里寻找一种方法来检查两个列表的内容是否不同。如果这是您想要的,您可以使用以下内容:-

    var differences = new HashSet(songs);
    differences.SymmetricExceptWith(attributes.Select(a => a.name));
    if (differences.Any())
    {
        // The lists differ.
    }
    

    【讨论】:

      【解决方案3】:

      这是查找所有未包含在属性名称中的歌曲的方法:

      var result = songs
        .Where(!attributes.Select(a => a.name).ToList().Contains(song));
      

      使用 except 的答案也很完美,可能更有效。

      编辑:如果您在 LINQ to SQL 中使用此 sintax,它有一个优势:它可以转换为 NOT IN SQL 谓词。 Except 不会被转换为 SQL 中的任何内容。因此,在这种情况下,所有记录都将从数据库中恢复,并在应用端除外,这样效率要低得多。

      【讨论】:

      • 如果使用Except 的其他答案完美且更高效,您为什么要发布此内容?
      • 如果你看到它,我在其他答案之前发布了这个,并在稍后添加了评论,明确说明其他解决方案更好。
      • “我在其他答案之前发布了这个。”你没有。
      • 是的,我缺少右括号。但看看发帖时间:我的 27 分钟前,编辑 20 分钟前; ionden 25 分钟前;我的 24 分钟前。但是我可以看到它冒犯了你,我会删除它。
      • 嘿,投票系统在这里是为了让人们知道哪个是最佳答案。这就是我投票给阿德里安的原因。但是,我认为看到不同的选择不会有什么坏处。我的至少有一个优势。请参阅我编辑的答案。
      【解决方案4】:
      var diff = songs.Except(attributes.Select(a => a.name)).ToList();
      

      【讨论】:

        猜你喜欢
        • 2012-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多