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

后端 未结 4 2046
广开言路
广开言路 2020-12-10 04:15

Ok so I have two lists in C#

List attributes = new List();
List songs = new List();


        
相关标签:
4条回答
  • 2020-12-10 04:55
    var difference = songs.Except(attributes.Select(s=>s.name)).ToList();
    

    edit

    Added ToList() to make it a list

    0 讨论(0)
  • 2020-12-10 04:57

    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.
    }
    
    0 讨论(0)
  • 2020-12-10 05:00
    var diff = songs.Except(attributes.Select(a => a.name)).ToList();
    
    0 讨论(0)
  • 2020-12-10 05:14

    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.

    0 讨论(0)
提交回复
热议问题