如何在C#中获得两个列表的差异

本文关键字:两个 列表 | 更新日期: 2023-09-27 18:28:43

好的,所以我在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);

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

所以对于伪码

difference = songs - attributes.names

如何在C#中获得两个列表的差异

var difference = songs.Except(attributes.Select(s=>s.name)).ToList();

编辑

添加ToList()使其成为列表

值得指出的是,这里发布的答案将返回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.
}

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

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

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

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

var diff = songs.Except(attributes.Select(a => a.name)).ToList();