pewocis495
pewocis495

Reputation: 117

Select different objects from two collections

I have the following class:

struct UserRecord
{
    //--- common settings
    int               login;                      // login
    int               leverage;                   // leverage
    int               enable;                     // enable
}

And I have two lists:

List<UserRecord> base_data = new List<UserRecord>();

base_data.Add(new UserRecord(){login = 1, leverage = 1000, enable = 0});
base_data.Add(new UserRecord(){login = 2, leverage = 100, enable = 0});
base_data.Add(new UserRecord(){login = 3, leverage = 10, enable = 1});
base_data.Add(new UserRecord(){login = 4, leverage = 10000, enable = 0});

List<UserRecord> snapshot_data= new List<UserRecord>();

snapshot_data.Add(new UserRecord(){login = 1, leverage = 1000, enable = 1});
snapshot_data.Add(new UserRecord(){login = 2, leverage = 100, enable = 0});
snapshot_data.Add(new UserRecord(){login = 3, leverage = 10, enable = 1});
snapshot_data.Add(new UserRecord(){login = 4, leverage = 10000, enable = 1});

My goal is to filter the records, and get the two records in a new list, that are with different fields, in this case only the field 'enable' is different.

var filtered_data = new List<UserRecord>(); // here records with login 1 and 4 should go.

Do you have any suggestions?

Upvotes: 1

Views: 269

Answers (1)

Yong Shun
Yong Shun

Reputation: 51160

You may look for Enumerable.Except() from System.Linq to find the differences between both enumerable.

using System.Linq;

List<UserRecord> filter_data = base_data.Except(snapshot_data)
            .ToList();

Demo @ .NET Fiddle


Another approach is if you just want to compare the difference in enable based on the items with the same login and leverage from the different lists.

You need to join both lists by the key(s) and query the record from the first list with the different enable value.

List<UserRecord> filter_data = (from a in base_data
                                join b in snapshot_data on new { a.login, a.leverage } equals new { b.login, b.leverage }
                                where a.enable != b.enable
                                select a
                                ).ToList();

Demo Solution 2 @ .NET Fiddle

Upvotes: 2

Related Questions