How do i get the difference in two lists in C#?

二次信任 提交于 2020-02-10 08:59:25

问题


Ok so I have two lists in C#

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

one is of strings and and one is of a attribute object that i created..very simple

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;
    }
}

I now have to compare to see what songs are not in the attributes name so for example

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

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

I want a way to return "another" and "yet another" because they are not in the attributes list name

so for pseudocode

difference = songs - attributes.names

回答1:


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

edit

Added ToList() to make it a list




回答2:


It's worth pointing out that the answers posted here will return a list of songs not present in attributes.names, but it won't give you a list of attributes.names not present in songs.

While this is what the OP wanted, the title may be a little misleading, especially if (like me) you came here looking for a way to check whether the contents of two lists differ. If this is what you want, you can use the following:-

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



回答3:


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



回答4:


This is the way to find all the songs which aren't included in attributes names:

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

The answer using Except is also perfect and probably more efficient.

EDIT: This sintax has one advantage if you're using it in LINQ to SQL: it translates into a NOT IN SQL predicate. Except is not translated to anything in SQL. So, in that context, all the records would be recovered from the database and excepted on the app side, which is much less efficient.



来源:https://stackoverflow.com/questions/9840539/how-do-i-get-the-difference-in-two-lists-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!